1 Commits

Author SHA1 Message Date
Sebastian b83b0952e6 fix(deps): update dependency vue-router to v5
Build Test / test (pull_request) Successful in 38s
JS Unit Tests / test (pull_request) Successful in 35s
PHP Unit Tests / test (pull_request) Successful in 1m9s
2026-05-15 12:23:41 +00:00
24 changed files with 2363 additions and 3652 deletions
@@ -1,59 +0,0 @@
name: PHP Integration Tests
on:
pull_request:
workflow_dispatch:
jobs:
test:
name: Integration Tests
runs-on: ubuntu-latest
services:
mongo:
image: mongo:8
options: >-
--health-cmd "mongosh --quiet --eval \"db.adminCommand('ping')\""
--health-interval 5s
--health-timeout 5s
--health-retries 12
steps:
- name: Retrieve Server Install Action
uses: actions/checkout@v6.0.2
with:
repository: Nodarx/action-server-install
ref: main
path: action-server-install
github-server-url: https://git.ktrix.dev
- name: Install server
uses: ./action-server-install
with:
install-php: 'true'
php-version: '8.5'
server-path: './server'
database-uri: 'mongodb://mongo:27017/?tls=false'
database-name: 'ktrix_ci'
app-environment: 'test'
- name: Checkout module under test
uses: actions/checkout@v6.0.2
with:
repository: ${{ github.repository }}
ref: ${{ github.event.pull_request.head.sha || github.sha }}
path: server/modules/provider_jmapc
github-server-url: https://git.ktrix.dev
- name: Install module dependencies
run: composer install --prefer-dist --no-progress
working-directory: server/modules/provider_jmapc
- name: Install and enable module
working-directory: server
run: |
php bin/console module:install provider_jmapc
php bin/console module:enable provider_jmapc
- name: Run integration tests
working-directory: server/modules/provider_jmapc
run: composer test:integration
+2 -8
View File
@@ -25,17 +25,11 @@ jobs:
tools: composer:v2
- name: Install Renovate
run: |
npm install --global --no-audit --fund=false \
--prefix "${{ runner.temp }}/renovate-npm" \
--cache "${{ runner.temp }}/renovate-npm-cache" \
renovate
"${{ runner.temp }}/renovate-npm/bin/renovate" --version
run: npm install -g renovate
- name: Run Renovate
env:
RENOVATE_TOKEN: ${{ secrets.RENOVATE_TOKEN }}
RENOVATE_PLATFORM: gitea
RENOVATE_ENDPOINT: https://git.ktrix.dev/api/v1
run: |
"${{ runner.temp }}/renovate-npm/bin/renovate" ${{ gitea.repository }}
run: renovate ${{ gitea.repository }}
+5 -1
View File
@@ -14,7 +14,11 @@ node_modules/
# Backend development
/lib/vendor/
coverage/
*.cache
phpunit.xml.cache
.phpunit.cache
.phpunit.result.cache
.php-cs-fixer.cache
.phpstan.cache
.phpactor/
# Editors
+5 -8
View File
@@ -10,7 +10,7 @@
"config": {
"optimize-autoloader": true,
"platform": {
"php": "8.3"
"php": "8.2"
},
"autoloader-suffix": "ProviderJmapc",
"vendor-dir": "lib/vendor",
@@ -25,13 +25,11 @@
}
],
"require": {
"guzzlehttp/guzzle": "^7.0",
"guzzlehttp/psr7": "^3.0",
"php": ">=8.3 <=8.5",
"php": ">=8.2 <=8.5",
"sebastiankrupinski/jmap-client-php": "dev-main"
},
"require-dev": {
"phpunit/phpunit": "^12.0"
"phpunit/phpunit": "^11.0"
},
"autoload": {
"psr-4": {
@@ -48,8 +46,7 @@
],
"post-update-cmd": [
],
"test:unit": "phpunit --configuration tests/php/phpunit.xml --testsuite \"Unit Tests\" --colors=always --testdox",
"test:integration": "phpunit --configuration tests/php/phpunit.xml --testsuite \"Integration Tests\" --colors=always --testdox",
"test:coverage": "XDEBUG_MODE=coverage phpunit --configuration tests/php/phpunit.xml --testsuite \"Unit Tests\" --coverage-html .phpunit.coverage --coverage-text"
"test:unit": "phpunit --configuration tests/php/phpunit.unit.xml --colors=always --testdox",
"test:coverage": "XDEBUG_MODE=coverage phpunit --configuration tests/php/phpunit.unit.xml --coverage-html .phpunit.coverage --coverage-text"
}
}
Generated
+407 -492
View File
File diff suppressed because it is too large Load Diff
@@ -9,7 +9,7 @@ declare(strict_types=1);
namespace KTXM\ProviderJmapc\Providers\Document;
use KTXF\Documents\Collection\CollectionPropertiesMutableAbstract;
use KTXF\Resource\Documents\Collection\CollectionPropertiesMutableAbstract;
/**
* Document Collection Properties Implementation
@@ -9,7 +9,7 @@ declare(strict_types=1);
namespace KTXM\ProviderJmapc\Providers\Document;
use KTXF\Documents\Collection\CollectionMutableAbstract;
use KTXF\Resource\Documents\Collection\CollectionMutableAbstract;
/**
* Document Collection Resource Implementation
+8 -8
View File
@@ -9,7 +9,7 @@ declare(strict_types=1);
namespace KTXM\ProviderJmapc\Providers\Document;
use KTXF\Documents\Entity\EntityPropertiesMutableAbstract;
use KTXF\Resource\Documents\Entity\EntityPropertiesMutableAbstract;
/**
* Document Collection Properties Implementation
@@ -24,23 +24,23 @@ class EntityProperties extends EntityPropertiesMutableAbstract {
public function fromJmap(array $parameters): static {
if (isset($data['size'])) {
$this->data[self::PROPERTY_SIZE] = (int) $data['size'];
$this->data[self::JSON_PROPERTY_SIZE] = (int) $data['size'];
}
if (isset($data['label'])) {
$this->data[self::PROPERTY_LABEL] = (string) $data['name'];
$this->data[self::JSON_PROPERTY_LABEL] = (string) $data['name'];
}
if (isset($data['mime'])) {
$this->data[self::PROPERTY_MIME] = (string) $data['type'];
$this->data[self::JSON_PROPERTY_MIME] = (string) $data['type'];
}
if (isset($data['format'])) {
$this->data[self::PROPERTY_FORMAT] = null;
$this->data[self::JSON_PROPERTY_FORMAT] = null;
}
if (isset($data['encoding'])) {
$this->data[self::PROPERTY_ENCODING] = null;
$this->data[self::JSON_PROPERTY_ENCODING] = null;
}
return $this;
@@ -52,8 +52,8 @@ class EntityProperties extends EntityPropertiesMutableAbstract {
public function toJmap(): array {
$parameters = array_filter([
'name' => $this->data[self::PROPERTY_LABEL],
'type' => $this->data[self::PROPERTY_MIME] ?? 'application/octet-stream'
'name' => $this->data[self::JSON_PROPERTY_LABEL],
'type' => $this->data[self::JSON_PROPERTY_MIME] ?? 'application/octet-stream'
], static fn($value) => $value !== null);
return $parameters;
+1 -1
View File
@@ -9,7 +9,7 @@ declare(strict_types=1);
namespace KTXM\ProviderJmapc\Providers\Document;
use KTXF\Documents\Entity\EntityMutableAbstract;
use KTXF\Resource\Documents\Entity\EntityMutableAbstract;
/**
* Mail Entity Resource Implementation
+13 -13
View File
@@ -9,11 +9,11 @@ declare(strict_types=1);
namespace KTXM\ProviderJmapc\Providers\Document;
use KTXF\Documents\Provider\ProviderBaseInterface;
use KTXF\Documents\Provider\ProviderServiceMutateInterface;
use KTXF\Documents\Provider\ProviderServiceTestInterface;
use KTXF\Documents\Service\ServiceBaseInterface;
use KTXF\Documents\Service\ServiceMutableInterface;
use KTXF\Resource\Documents\Provider\ProviderBaseInterface;
use KTXF\Resource\Documents\Provider\ProviderServiceMutateInterface;
use KTXF\Resource\Documents\Provider\ProviderServiceTestInterface;
use KTXF\Resource\Documents\Service\ServiceBaseInterface;
use KTXF\Resource\Documents\Service\ServiceMutableInterface;
use KTXF\Resource\Provider\ResourceServiceLocationInterface;
use KTXF\Resource\Provider\ResourceServiceMutateInterface;
use KTXM\ProviderJmapc\Service\Discovery;
@@ -21,9 +21,9 @@ use KTXM\ProviderJmapc\Service\Remote\RemoteService;
use KTXM\ProviderJmapc\Stores\ServiceStore;
/**
* JMAP Documents Provider
* JMAP Mail Provider
*/
class Provider implements ProviderBaseInterface, ProviderServiceMutateInterface, ProviderServiceTestInterface
class Provider implements ProviderServiceMutateInterface, ProviderServiceTestInterface
{
public const JSON_TYPE = ProviderBaseInterface::JSON_TYPE;
@@ -49,10 +49,10 @@ class Provider implements ProviderBaseInterface, ProviderServiceMutateInterface,
public function jsonSerialize(): array
{
return [
self::PROPERTY_TYPE => self::JSON_TYPE,
self::PROPERTY_IDENTIFIER => self::PROVIDER_IDENTIFIER,
self::PROPERTY_LABEL => self::PROVIDER_LABEL,
self::PROPERTY_CAPABILITIES => $this->providerAbilities,
self::JSON_PROPERTY_TYPE => self::JSON_TYPE,
self::JSON_PROPERTY_IDENTIFIER => self::PROVIDER_IDENTIFIER,
self::JSON_PROPERTY_LABEL => self::PROVIDER_LABEL,
self::JSON_PROPERTY_CAPABILITIES => $this->providerAbilities,
];
}
@@ -63,7 +63,7 @@ class Provider implements ProviderBaseInterface, ProviderServiceMutateInterface,
public function type(): string
{
return self::TYPE_DOCUMENT;
return self::TYPE_MAIL;
}
public function identifier(): string
@@ -170,7 +170,7 @@ class Provider implements ProviderBaseInterface, ProviderServiceMutateInterface,
return $discovery->discover($identity, $location, $secret, $verifySSL);
}
public function serviceTest(ServiceBaseInterface|ServiceMutableInterface $service, array $options = []): array {
public function serviceTest(ServiceBaseInterface $service, array $options = []): array {
$startTime = microtime(true);
try {
+72 -92
View File
@@ -10,20 +10,17 @@ declare(strict_types=1);
namespace KTXM\ProviderJmapc\Providers\Document;
use Generator;
use KTXF\Documents\Collection\CollectionBaseInterface;
use KTXF\Documents\Collection\CollectionMutableInterface;
use KTXF\Documents\Collection\CollectionPropertiesBaseInterface;
use KTXF\Documents\Service\ServiceBaseInterface;
use KTXF\Documents\Service\ServiceCollectionMutableInterface;
use KTXF\Documents\Service\ServiceConfigurableInterface;
use KTXF\Documents\Service\ServiceMutableInterface;
use KTXF\Resource\Delta\Delta;
use KTXF\Resource\Filter\Filter;
use KTXF\Resource\Filter\IFilter;
use KTXF\Resource\Identifier\CollectionIdentifierInterface;
use KTXF\Resource\Identifier\EntityIdentifierInterface;
use KTXF\Resource\Provider\ResourceServiceIdentityInterface;
use KTXF\Resource\Provider\ResourceServiceLocationInterface;
use KTXF\Resource\Delta\Delta;
use KTXF\Resource\Documents\Collection\CollectionBaseInterface;
use KTXF\Resource\Documents\Collection\CollectionMutableInterface;
use KTXF\Resource\Documents\Service\ServiceBaseInterface;
use KTXF\Resource\Documents\Service\ServiceCollectionMutableInterface;
use KTXF\Resource\Documents\Service\ServiceConfigurableInterface;
use KTXF\Resource\Documents\Service\ServiceMutableInterface;
use KTXF\Resource\Filter\Filter;
use KTXF\Resource\Filter\IFilter;
use KTXF\Resource\Range\IRange;
use KTXF\Resource\Range\Range;
use KTXF\Resource\Range\RangeType;
@@ -128,15 +125,15 @@ class Service implements ServiceBaseInterface, ServiceMutableInterface, ServiceC
public function jsonSerialize(): array {
return array_filter([
self::PROPERTY_TYPE => self::JSON_TYPE,
self::PROPERTY_PROVIDER => self::PROVIDER_IDENTIFIER,
self::PROPERTY_IDENTIFIER => $this->serviceIdentifier,
self::PROPERTY_LABEL => $this->serviceLabel,
self::PROPERTY_ENABLED => $this->serviceEnabled,
self::PROPERTY_CAPABILITIES => $this->serviceAbilities,
self::PROPERTY_LOCATION => $this->location?->jsonSerialize(),
self::PROPERTY_IDENTITY => $this->identity?->jsonSerialize(),
self::PROPERTY_AUXILIARY => $this->auxiliary,
self::JSON_PROPERTY_TYPE => self::JSON_TYPE,
self::JSON_PROPERTY_PROVIDER => self::PROVIDER_IDENTIFIER,
self::JSON_PROPERTY_IDENTIFIER => $this->serviceIdentifier,
self::JSON_PROPERTY_LABEL => $this->serviceLabel,
self::JSON_PROPERTY_ENABLED => $this->serviceEnabled,
self::JSON_PROPERTY_CAPABILITIES => $this->serviceAbilities,
self::JSON_PROPERTY_LOCATION => $this->location?->jsonSerialize(),
self::JSON_PROPERTY_IDENTITY => $this->identity?->jsonSerialize(),
self::JSON_PROPERTY_AUXILIARY => $this->auxiliary,
], fn($v) => $v !== null);
}
@@ -145,20 +142,20 @@ class Service implements ServiceBaseInterface, ServiceMutableInterface, ServiceC
$data = json_decode($data, true, 512, JSON_THROW_ON_ERROR);
}
if (isset($data[self::PROPERTY_LABEL])) {
$this->setLabel($data[self::PROPERTY_LABEL]);
if (isset($data[self::JSON_PROPERTY_LABEL])) {
$this->setLabel($data[self::JSON_PROPERTY_LABEL]);
}
if (isset($data[self::PROPERTY_ENABLED])) {
$this->setEnabled($data[self::PROPERTY_ENABLED]);
if (isset($data[self::JSON_PROPERTY_ENABLED])) {
$this->setEnabled($data[self::JSON_PROPERTY_ENABLED]);
}
if (isset($data[self::PROPERTY_LOCATION])) {
$this->setLocation($this->freshLocation(null, $data[self::PROPERTY_LOCATION]));
if (isset($data[self::JSON_PROPERTY_LOCATION])) {
$this->setLocation($this->freshLocation(null, $data[self::JSON_PROPERTY_LOCATION]));
}
if (isset($data[self::PROPERTY_IDENTITY])) {
$this->setIdentity($this->freshIdentity(null, $data[self::PROPERTY_IDENTITY]));
if (isset($data[self::JSON_PROPERTY_IDENTITY])) {
$this->setIdentity($this->freshIdentity(null, $data[self::JSON_PROPERTY_IDENTITY]));
}
if (isset($data[self::PROPERTY_AUXILIARY]) && is_array($data[self::PROPERTY_AUXILIARY])) {
$this->setAuxiliary($data[self::PROPERTY_AUXILIARY]);
if (isset($data[self::JSON_PROPERTY_AUXILIARY]) && is_array($data[self::JSON_PROPERTY_AUXILIARY])) {
$this->setAuxiliary($data[self::JSON_PROPERTY_AUXILIARY]);
}
return $this;
@@ -319,30 +316,18 @@ class Service implements ServiceBaseInterface, ServiceMutableInterface, ServiceC
return new CollectionResource(provider: $this->provider(), service: $this->identifier());
}
/**
* Convert incoming collection properties into a native CollectionResource
*/
private function collectionNative(CollectionPropertiesBaseInterface $properties, string|int|null $identifier = null): CollectionResource
{
if ($properties instanceof CollectionResource) {
return clone $properties;
}
$object = new CollectionResource(provider: $this->provider(), service: $this->identifier());
$object->jsonDeserialize(array_filter([
CollectionResource::PROPERTY_IDENTIFIER => $identifier,
CollectionResource::PROPERTY_PROPERTIES => $properties->jsonSerialize(),
], fn($v) => $v !== null));
return $object;
}
public function collectionCreate(CollectionIdentifierInterface|null $target, CollectionPropertiesBaseInterface $properties, array $options = []): CollectionBaseInterface
public function collectionCreate(string|int|null $location, CollectionMutableInterface $collection, array $options = []): CollectionBaseInterface
{
$this->initialize();
$collection = $this->collectionNative($properties);
if ($collection instanceof CollectionResource === false) {
$object = new CollectionResource(provider: $this->provider(), service: $this->identifier());
$object->jsonDeserialize($collection->jsonSerialize());
$collection = $object;
}
$collection = $collection->toJmap();
$collection = $this->remoteService->collectionCreate($target?->collection(), $collection, $options);
$collection = $this->remoteService->collectionCreate($location, $collection, $options);
$object = new CollectionResource(provider: $this->provider(), service: $this->identifier());
$object->fromJmap($collection);
@@ -350,12 +335,15 @@ class Service implements ServiceBaseInterface, ServiceMutableInterface, ServiceC
return $object;
}
public function collectionUpdate(CollectionIdentifierInterface $target, CollectionPropertiesBaseInterface $properties): CollectionBaseInterface
public function collectionUpdate(string|int $identifier, CollectionMutableInterface $collection): CollectionBaseInterface
{
$this->initialize();
$identifier = $target->collection();
$collection = $this->collectionNative($properties, $identifier);
if ($collection instanceof CollectionResource === false) {
$object = new CollectionResource(provider: $this->provider(), service: $this->identifier());
$object->jsonDeserialize($collection->jsonSerialize());
$collection = $object;
}
$collection = $collection->toJmap();
$collection = $this->remoteService->collectionModify($identifier, $collection);
@@ -366,17 +354,14 @@ class Service implements ServiceBaseInterface, ServiceMutableInterface, ServiceC
return $object;
}
public function collectionDelete(CollectionIdentifierInterface $target, bool $force = false): CollectionBaseInterface | true
public function collectionDelete(string|int $identifier, bool $force = false, bool $recursive = false): bool
{
$this->initialize();
if ($this->remoteService->collectionDestroy($target->collection(), $force, $force) === null) {
throw new \RuntimeException("Failed to delete collection: {$target->collection()}");
}
return true;
return $this->remoteService->collectionDestroy($identifier, $force, $recursive) !== null;
}
public function collectionMove(CollectionIdentifierInterface|null $target, CollectionIdentifierInterface $source): CollectionBaseInterface
public function collectionMove(string|int $identifier, string|int|null $targetLocation): CollectionBaseInterface
{
// TODO: Implement collection move
$this->initialize();
@@ -384,20 +369,12 @@ class Service implements ServiceBaseInterface, ServiceMutableInterface, ServiceC
return $collection;
}
public function collectionCopy(CollectionIdentifierInterface|null $target, CollectionIdentifierInterface $source): CollectionBaseInterface
{
// TODO: Implement collection copy
$this->initialize();
$collection = new CollectionResource(provider: $this->provider(), service: $this->identifier());
return $collection;
}
// Entity operations
public function entityListBulk(string|int|null $collection, ?IFilter $filter = null, ?ISort $sort = null, ?IRange $range = null, ?array $properties = null): array
public function entityList(string|int|null $collection, ?IFilter $filter = null, ?ISort $sort = null, ?IRange $range = null, ?array $properties = null): array
{
$this->initialize();
$result = $this->remoteService->entityList($collection, $filter, $sort, $range, $properties);
$list = [];
@@ -413,7 +390,7 @@ class Service implements ServiceBaseInterface, ServiceMutableInterface, ServiceC
return $list;
}
public function entityListStream(string|int|null $collection, ?IFilter $filter = null, ?ISort $sort = null, ?IRange $range = null, ?array $properties = null): Generator
public function entityListStream(string|int $collection, ?IFilter $filter = null, ?ISort $sort = null, ?IRange $range = null, ?array $properties = null): Generator
{
$this->initialize();
@@ -444,11 +421,11 @@ class Service implements ServiceBaseInterface, ServiceMutableInterface, ServiceC
return new Range();
}
public function entityDelta(string|int|null $collection, string $signature): Delta
public function entityDelta(string|int|null $collection, string $signature, string $detail = 'ids'): Delta
{
$this->initialize();
return $this->remoteService->entityDelta($collection, $signature, 'ids');
return $this->remoteService->entityDelta($collection, $signature, $detail);
}
public function entityExtant(string|int|null $collection, string|int ...$identifiers): array
@@ -458,45 +435,48 @@ class Service implements ServiceBaseInterface, ServiceMutableInterface, ServiceC
return $this->remoteService->entityExtant(...$identifiers);
}
public function entityFetchBulk(EntityIdentifierInterface ...$identifiers): array
public function entityFetch(string|int|null $collection, string|int ...$identifiers): array
{
$this->initialize();
$entityIds = array_map(fn($identifier) => $identifier->entity(), $identifiers);
$entities = $this->remoteService->entityFetch(...$entityIds);
$list = [];
foreach ($entities as $key => $entity) {
$entities = $this->remoteService->entityFetch(...$identifiers);
foreach ($entities as &$entity) {
if (is_array($entity) && isset($entity['id'])) {
$object = new EntityResource(provider: $this->provider(), service: $this->identifier());
$object->fromJmap($entity);
$list[$object->identifier()] = $object;
} else {
$list[$key] = $entity;
$entity = $object;
}
}
return $list;
return $entities;
}
public function entityFetchStream(EntityIdentifierInterface ...$identifiers): Generator
{
yield from $this->entityFetchBulk(...$identifiers);
}
public function entityRead(EntityIdentifierInterface $target): ?string
public function entityRead(string|int|null $collection, string|int $identifier): ?string
{
return null;
}
public function entityReadStream(EntityIdentifierInterface $target)
// Node operations
public function nodeList(string|int|null $collection, bool $recursive = false, ?IFilter $filter = null, ?ISort $sort = null, ?IRange $range = null, ?array $properties = null): array
{
return null;
return [];
}
public function entityReadChunk(EntityIdentifierInterface $target, int $offset, int $length): ?string
public function nodeListFilter(): IFilter
{
return null;
return new Filter(['']);
}
public function nodeListSort(): ISort
{
return new Sort(['']);
}
public function nodeDelta(string|int|null $collection, string $signature, string $detail = 'ids'): Delta
{
return new Delta();
}
}
+186
View File
@@ -0,0 +1,186 @@
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: Sebastian Krupinski <krupinski01@gmail.com>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace KTXM\ProviderJmapc\Providers\Mail;
/**
* Mail Attachment Object
*
* @since 30.0.0
*/
class MessageAttachment implements MessagePart {
protected MessagePart $_meta;
protected ?string $_contents = null;
public function __construct(?MessagePart $meta = null, ?string $contents = null) {
// determine if meta data exists
// if meta data is missing create new
if ($meta === null) {
$meta = new MessagePart();
$meta->setDisposition('attachment');
$meta->setType('application/octet-stream');
}
$this->setParameters($meta);
// determine if attachment contents exists
// if contents exists set the contents
if ($contents !== null) {
$this->setContents($contents);
}
}
/**
* sets the attachments parameters
*
* @since 1.0.0
*
* @param MessagePart|null $meta collection of all message parameters
*
* @return self return this object for command chaining
*/
public function setParameters(?MessagePart $meta): self {
// replace meta data store
$this->_meta = $meta;
// return this object for command chaining
return $this;
}
/**
* gets the attachments of this message
*
* @since 1.0.0
*
* @return array collection of all message parameters
*/
public function getParameters(): MessagePart {
// evaluate if data store field exists and return value(s) or null otherwise
return $this->_meta;
}
/**
* arbitrary unique text string identifying this message
*
* @since 1.0.0
*
* @return string id of this message
*/
public function id(): string {
// return id of message
return $this->_meta->getBlobId();
}
/**
* sets the attachment file name
*
* @since 30.0.0
*
* @param string $value file name (e.g example.txt)
*
* @return self return this object for command chaining
*/
public function setName(string $value): self {
$this->_meta->setName($value);
return $this;
}
/**
* gets the attachment file name
*
* @since 30.0.0
*
* @return string | null returns the attachment file name or null if not set
*/
public function getName(): ?string {
return $this->_meta->getName();
}
/**
* sets the attachment mime type
*
* @since 30.0.0
*
* @param string $value mime type (e.g. text/plain)
*
* @return self return this object for command chaining
*/
public function setType(string $value): self {
$this->_meta->setType($value);
return $this;
}
/**
* gets the attachment mime type
*
* @since 30.0.0
*
* @return string | null returns the attachment mime type or null if not set
*/
public function getType(): ?string {
return $this->_meta->getType();
}
/**
* sets the attachment contents (actual data)
*
* @since 30.0.0
*
* @param string $value binary contents of file
*
* @return self return this object for command chaining
*/
public function setContents(string $value): self {
$this->_contents = $value;
return $this;
}
/**
* gets the attachment contents (actual data)
*
* @since 30.0.0
*
* @return string | null returns the attachment contents or null if not set
*/
public function getContents(): ?string {
return $this->_contents;
}
/**
* sets the embedded status of the attachment
*
* @since 30.0.0
*
* @param bool $value true - embedded / false - not embedded
*
* @return self return this object for command chaining
*/
public function setEmbedded(bool $value): self {
if ($value) {
$this->_meta->setDisposition('inline');
} else {
$this->_meta->setDisposition('attachment');
}
return $this;
}
/**
* gets the embedded status of the attachment
*
* @since 30.0.0
*
* @return bool embedded status of the attachment
*/
public function getEmbedded(): bool {
if ($this->_meta->getDisposition() === 'inline') {
return true;
} else {
return false;
}
}
}
+82 -211
View File
@@ -16,142 +16,6 @@ use KTXF\Mail\Object\MessagePropertiesMutableAbstract;
*/
class MessageProperties extends MessagePropertiesMutableAbstract {
private function buildJmapBodyStructure(array &$bodyValues): ?array {
$counter = 0;
$body = isset($this->data[static::PROPERTY_BODY]) && is_array($this->data[static::PROPERTY_BODY])
? $this->serializeBodyPartForJmap($this->data[static::PROPERTY_BODY], $bodyValues, $counter)
: null;
$attachments = [];
if (isset($this->data[static::PROPERTY_ATTACHMENTS]) && is_array($this->data[static::PROPERTY_ATTACHMENTS])) {
foreach ($this->data[static::PROPERTY_ATTACHMENTS] as $attachment) {
if (!is_array($attachment)) {
continue;
}
$serialized = $this->serializeBodyPartForJmap($attachment, $bodyValues, $counter);
if ($serialized !== null) {
$attachments[] = $serialized;
}
}
}
if ($body === null) {
if ($attachments === []) {
return null;
}
if (count($attachments) === 1) {
return $attachments[0];
}
return [
'type' => 'multipart/mixed',
'subParts' => $attachments,
];
}
if ($attachments === []) {
return $body;
}
return [
'type' => 'multipart/mixed',
'subParts' => array_merge([$body], $attachments),
];
}
private function serializeBodyPartForJmap(array $part, array &$bodyValues, int &$counter): ?array {
$type = isset($part['type']) && is_string($part['type']) && $part['type'] !== ''
? strtolower($part['type'])
: null;
if ($type === null) {
return null;
}
$isMultipart = str_starts_with($type, 'multipart/');
$serialized = [
'type' => $type,
];
if (isset($part['name']) && is_string($part['name']) && $part['name'] !== '') {
$serialized['name'] = $part['name'];
}
if (isset($part['disposition']) && is_string($part['disposition']) && $part['disposition'] !== '') {
$serialized['disposition'] = $part['disposition'];
}
if (isset($part['cid']) && is_string($part['cid']) && $part['cid'] !== '') {
$serialized['cid'] = $part['cid'];
}
if (isset($part['language']) && is_array($part['language']) && $part['language'] !== []) {
$serialized['language'] = $part['language'];
}
if (isset($part['location']) && is_string($part['location']) && $part['location'] !== '') {
$serialized['location'] = $part['location'];
}
if ($isMultipart) {
$subParts = [];
foreach ($part['subParts'] ?? [] as $subPart) {
if (!is_array($subPart)) {
continue;
}
$serializedSubPart = $this->serializeBodyPartForJmap($subPart, $bodyValues, $counter);
if ($serializedSubPart !== null) {
$subParts[] = $serializedSubPart;
}
}
if ($subParts !== []) {
$serialized['subParts'] = $subParts;
}
return $serialized;
}
$blobId = isset($part['blobId']) && is_string($part['blobId']) && $part['blobId'] !== ''
? $part['blobId']
: null;
$content = isset($part['content']) && is_string($part['content']) ? $part['content'] : null;
if ($blobId !== null) {
$serialized['blobId'] = $blobId;
if (isset($part['charset']) && is_string($part['charset']) && $part['charset'] !== '' && str_starts_with($type, 'text/')) {
$serialized['charset'] = $part['charset'];
}
if (isset($part['size']) && is_int($part['size'])) {
$serialized['size'] = $part['size'];
}
return $serialized;
}
if ($content !== null && str_starts_with($type, 'text/')) {
$partId = isset($part['partId']) && is_string($part['partId']) && $part['partId'] !== ''
? $part['partId']
: 'part-' . (++$counter);
$serialized['partId'] = $partId;
$bodyValues[$partId] = [
'value' => $content,
'isEncodingProblem' => false,
'isTruncated' => false,
];
return $serialized;
}
return $serialized;
}
/**
* Convert JMAP parameters array to mail message properties object
*
@@ -159,91 +23,91 @@ class MessageProperties extends MessagePropertiesMutableAbstract {
*/
public function fromJmap(array $parameters): static {
if (isset($parameters['size'])) {
$this->data[static::PROPERTY_SIZE] = $parameters['size'];
}
if (isset($parameters['headers']) && is_array($parameters['headers'])) {
$this->data[static::PROPERTY_HEADERS] = $parameters['headers'];
}
if (isset($parameters['messageId'])) {
$this->data[static::PROPERTY_URID] = $parameters['messageId'][0];
$this->data['urid'] = $parameters['messageId'][0];
}
if (isset($parameters['size'])) {
$this->data['size'] = $parameters['size'];
}
if (isset($parameters['receivedAt'])) {
$this->data[static::PROPERTY_RECEIVED] = $parameters['receivedAt'];
$this->data['received'] = $parameters['receivedAt'];
}
if (isset($parameters['sentAt'])) {
$this->data[static::PROPERTY_SENT] = $parameters['sentAt'];
$this->data['date'] = $parameters['sentAt'];
}
if (isset($parameters['inReplyTo'])) {
$this->data[static::PROPERTY_IN_REPLY_TO] = $parameters['inReplyTo'];
$this->data['inReplyTo'] = $parameters['inReplyTo'];
}
if (isset($parameters['references'])) {
$this->data[static::PROPERTY_REFERENCES] = is_array($parameters['references']) ? $parameters['references'] : [];
$this->data['references'] = is_array($parameters['references']) ? $parameters['references'] : [];
}
if (isset($parameters['subject'])) {
$this->data['subject'] = $parameters['subject'];
}
if (isset($parameters['preview'])) {
$this->data['snippet'] = $parameters['preview'];
}
if (isset($parameters['sender'])) {
$this->data[static::PROPERTY_SENDER] = $parameters['sender'];
$this->data['sender'] = $parameters['sender'];
}
if (isset($parameters['from']) && is_array($parameters['from']) && !empty($parameters['from'])) {
$this->data[static::PROPERTY_FROM] = [
$this->data['from'] = [
'address' => $parameters['from'][0]['email'] ?? '',
'label' => $parameters['from'][0]['name'] ?? null
];
}
if (isset($parameters['replyTo']) && is_array($parameters['replyTo'])) {
$this->data[static::PROPERTY_REPLY_TO] = [];
foreach ($parameters['replyTo'] as $addr) {
$this->data[static::PROPERTY_REPLY_TO][] = [
'address' => $addr['email'] ?? '',
'label' => $addr['name'] ?? null
];
}
}
if (isset($parameters['to']) && is_array($parameters['to'])) {
$this->data[static::PROPERTY_TO] = [];
$this->data['to'] = [];
foreach ($parameters['to'] as $addr) {
$this->data[static::PROPERTY_TO][] = [
$this->data['to'][] = [
'address' => $addr['email'] ?? '',
'label' => $addr['name'] ?? null
];
}
}
if (isset($parameters['cc']) && is_array($parameters['cc'])) {
$this->data[static::PROPERTY_CC] = [];
$this->data['cc'] = [];
foreach ($parameters['cc'] as $addr) {
$this->data[static::PROPERTY_CC][] = [
$this->data['cc'][] = [
'address' => $addr['email'] ?? '',
'label' => $addr['name'] ?? null
];
}
}
if (isset($parameters['bcc']) && is_array($parameters['bcc'])) {
$this->data[static::PROPERTY_BCC] = [];
$this->data['bcc'] = [];
foreach ($parameters['bcc'] as $addr) {
$this->data[static::PROPERTY_BCC][] = [
$this->data['bcc'][] = [
'address' => $addr['email'] ?? '',
'label' => $addr['name'] ?? null
];
}
}
if (isset($parameters['subject'])) {
$this->data[static::PROPERTY_SUBJECT] = $parameters['subject'];
if (isset($parameters['replyTo']) && is_array($parameters['replyTo'])) {
$this->data['replyTo'] = [];
foreach ($parameters['replyTo'] as $addr) {
$this->data['replyTo'][] = [
'address' => $addr['email'] ?? '',
'label' => $addr['name'] ?? null
];
}
}
if (isset($parameters['keywords']) && is_array($parameters['keywords'])) {
$this->data['flags'] = [];
foreach ($parameters['keywords'] as $keyword => $value) {
$flag = match($keyword) {
'$seen' => 'read',
'$flagged' => 'flagged',
'$answered' => 'answered',
'$draft' => 'draft',
'$deleted' => 'deleted',
default => $keyword
};
$this->data['flags'][$flag] = $value;
}
}
if (isset($parameters['bodyStructure'])) {
$this->data[static::PROPERTY_BODY] = $parameters['bodyStructure'];
$this->data['body'] = $parameters['bodyStructure'];
// Recursively add content from bodyValues to matching parts
if (isset($parameters['bodyValues']) && is_array($parameters['bodyValues'])) {
$addContentToParts = function(&$structure, $bodyValues) use (&$addContentToParts) {
@@ -259,27 +123,14 @@ class MessageProperties extends MessagePropertiesMutableAbstract {
}
};
$addContentToParts($this->data[static::PROPERTY_BODY], $parameters['bodyValues']);
$addContentToParts($this->data['body'], $parameters['bodyValues']);
}
}
if (isset($parameters['headers']) && is_array($parameters['headers'])) {
$this->data['headers'] = $parameters['headers'];
}
if (isset($parameters['attachments'])) {
$this->data[static::PROPERTY_ATTACHMENTS] = $parameters['attachments'];
}
if (isset($parameters['keywords']) && is_array($parameters['keywords'])) {
$this->data[static::PROPERTY_FLAGS] = [];
foreach ($parameters['keywords'] as $keyword => $value) {
$flag = match($keyword) {
'$seen' => 'seen',
'$flagged' => 'flagged',
'$answered' => 'answered',
'$draft' => 'draft',
'$deleted' => 'deleted',
default => $keyword
};
$this->data[static::PROPERTY_FLAGS][$flag] = $value;
}
$this->data['attachments'] = $parameters['attachments'];
}
return $this;
@@ -298,11 +149,11 @@ class MessageProperties extends MessagePropertiesMutableAbstract {
if (isset($this->data['size'])) {
$parameters['size'] = $this->data['size'];
}
if (isset($this->data['received'])) {
$parameters['receivedAt'] = $this->data['received'];
if (isset($this->data['receivedDate'])) {
$parameters['receivedAt'] = $this->data['receivedDate'];
}
if (isset($this->data['sent'])) {
$parameters['sentAt'] = $this->data['sent'];
if (isset($this->data['date'])) {
$parameters['sentAt'] = $this->data['date'];
}
if (isset($this->data['inReplyTo'])) {
$parameters['inReplyTo'] = $this->data['inReplyTo'];
@@ -365,7 +216,7 @@ class MessageProperties extends MessagePropertiesMutableAbstract {
$parameters['keywords'] = [];
foreach ($this->data['flags'] as $flag => $value) {
$keyword = match($flag) {
'seen' => '$seen',
'read' => '$seen',
'flagged' => '$flagged',
'answered' => '$answered',
'draft' => '$draft',
@@ -375,17 +226,37 @@ class MessageProperties extends MessagePropertiesMutableAbstract {
$parameters['keywords'][$keyword] = $value;
}
}
$bodyValues = [];
$bodyStructure = $this->buildJmapBodyStructure($bodyValues);
if ($bodyStructure !== null) {
$parameters['bodyStructure'] = $bodyStructure;
$parameters['bodyValues'] = $bodyValues;
if (isset($this->data['bodyStructure'])) {
$parameters['bodyStructure'] = $this->data['bodyStructure'];
}
if (isset($this->data['body'])) {
$parameters['bodyValues'] = [];
if (isset($this->data['body']['text']['content'])) {
$parameters['bodyValues']['0'] = [
'value' => $this->data['body']['text']['content'],
'isEncodingProblem' => false,
'isTruncated' => false
];
}
if (isset($this->data['body']['html']['content'])) {
$parameters['bodyValues']['1'] = [
'value' => $this->data['body']['html']['content'],
'isEncodingProblem' => false,
'isTruncated' => false
];
}
}
if (isset($this->data['headers'])) {
$parameters['headers'] = $this->data['headers'];
}
if (isset($this->data['attachments'])) {
$parameters['attachments'] = $this->data['attachments'];
$parameters['hasAttachment'] = !empty($this->data['attachments']);
} else {
$parameters['hasAttachment'] = false;
}
return $parameters;
}
+15 -12
View File
@@ -14,16 +14,19 @@ use KTXF\Mail\Provider\ProviderServiceDiscoverInterface;
use KTXF\Mail\Provider\ProviderServiceMutateInterface;
use KTXF\Mail\Provider\ProviderServiceTestInterface;
use KTXF\Mail\Service\ServiceBaseInterface;
use KTXF\Mail\Service\ServiceMutableInterface;
use KTXF\Resource\Provider\ResourceServiceLocationInterface;
use KTXF\Resource\Provider\ResourceServiceMutateInterface;
use KTXM\ProviderJmapc\Service\Discovery;
use KTXM\ProviderJmapc\Service\Remote\RemoteService;
use KTXM\ProviderJmapc\Stores\ServiceStore;
class Provider implements ProviderBaseInterface, ProviderServiceMutateInterface, ProviderServiceDiscoverInterface, ProviderServiceTestInterface
/**
* JMAP Mail Provider
*/
class Provider implements ProviderServiceMutateInterface, ProviderServiceDiscoverInterface, ProviderServiceTestInterface
{
public const JSON_TYPE = ProviderBaseInterface::JSON_TYPE;
protected const PROVIDER_IDENTIFIER = 'jmap';
protected const PROVIDER_LABEL = 'JMAP Mail Provider';
protected const PROVIDER_DESCRIPTION = 'Provides mail services via JMAP protocol (RFC 8620)';
@@ -46,10 +49,10 @@ class Provider implements ProviderBaseInterface, ProviderServiceMutateInterface,
public function jsonSerialize(): array
{
return [
self::PROPERTY_TYPE => self::JSON_TYPE,
self::PROPERTY_IDENTIFIER => self::PROVIDER_IDENTIFIER,
self::PROPERTY_LABEL => self::PROVIDER_LABEL,
self::PROPERTY_CAPABILITIES => $this->providerAbilities,
self::JSON_PROPERTY_TYPE => self::JSON_TYPE,
self::JSON_PROPERTY_IDENTIFIER => self::PROVIDER_IDENTIFIER,
self::JSON_PROPERTY_LABEL => self::PROVIDER_LABEL,
self::JSON_PROPERTY_CAPABILITIES => $this->providerAbilities,
];
}
@@ -142,7 +145,7 @@ class Provider implements ProviderBaseInterface, ProviderServiceMutateInterface,
}
$created = $this->serviceStore->create($tenantId, $userId, $service);
return (string) $created['sid'];
return (string) $created['id'];
}
public function serviceModify(string $tenantId, string $userId, ResourceServiceMutateInterface $service): string
@@ -151,8 +154,8 @@ class Provider implements ProviderBaseInterface, ProviderServiceMutateInterface,
throw new \InvalidArgumentException('Service must be instance of JMAP Service');
}
$this->serviceStore->modify($tenantId, $userId, $service);
return (string) $service->identifier();
$updated = $this->serviceStore->modify($tenantId, $userId, $service);
return (string) $updated['id'];
}
public function serviceDestroy(string $tenantId, string $userId, ResourceServiceMutateInterface $service): bool
@@ -177,8 +180,7 @@ class Provider implements ProviderBaseInterface, ProviderServiceMutateInterface,
return $discovery->discover($identity, $location, $secret, $verifySSL);
}
public function serviceTest(ServiceBaseInterface|ServiceMutableInterface $service, array $options = []): array
{
public function serviceTest(ServiceBaseInterface $service, array $options = []): array {
$startTime = microtime(true);
try {
@@ -197,7 +199,8 @@ class Provider implements ProviderBaseInterface, ProviderServiceMutateInterface,
. ' (Account ID: ' . ($session->username() ?? 'N/A') . ')'
. ' (Latency: ' . $latency . ' ms)',
];
} catch (\Throwable $e) {
} catch (\Exception $e) {
$latency = round((microtime(true) - $startTime) * 1000);
return [
'success' => false,
'message' => 'Test failed: ' . $e->getMessage(),
File diff suppressed because it is too large Load Diff
+110 -216
View File
@@ -11,6 +11,8 @@ namespace KTXM\ProviderJmapc\Service\Remote;
use Exception;
use JmapClient\Client;
use JmapClient\Requests\Blob\BlobGet;
use JmapClient\Requests\Blob\BlobSet;
use JmapClient\Requests\Mail\MailboxGet;
use JmapClient\Requests\Mail\MailboxParameters as MailboxParametersRequest;
use JmapClient\Requests\Mail\MailboxQuery;
@@ -23,16 +25,17 @@ use JmapClient\Requests\Mail\MailQuery;
use JmapClient\Requests\Mail\MailQueryChanges;
use JmapClient\Requests\Mail\MailSet;
use JmapClient\Requests\Mail\MailSubmissionSet;
use JmapClient\Requests\RequestBundle;
use JmapClient\Responses\Mail\MailboxParameters as MailboxParametersResponse;
use JmapClient\Responses\Mail\MailPart;
use JmapClient\Responses\Mail\MailParameters as MailParametersResponse;
use JmapClient\Responses\ResponseException;
use KTXF\Resource\BinaryResource;
use KTXF\Resource\Delta\Delta;
use KTXF\Resource\Delta\DeltaCollection;
use KTXF\Resource\Filter\Filter;
use KTXF\Resource\Filter\IFilter;
use KTXF\Resource\Range\IRange;
use KTXF\Resource\Range\IRangeTally;
use KTXF\Resource\Range\Range;
use KTXF\Resource\Range\RangeAnchorType;
use KTXF\Resource\Range\RangeTally;
use KTXF\Resource\Sort\ISort;
@@ -493,103 +496,6 @@ class RemoteMailService {
return new RangeTally();
}
/**
* retrieve entity from remote storage
*
* @since Release 1.0.0
*/
public function entityFetch(string ...$identifiers): ?array {
// construct request
$r0 = new MailGet($this->dataAccount, null, $this->resourceNamespace, $this->resourceEntityLabel);
$r0->target(...$identifiers);
// select properties to return
$r0->property(...$this->defaultMailProperties);
$r0->bodyAll(true);
// transceive
$bundle = $this->dataStore->perform([$r0]);
// extract response
$response = $bundle->response(0);
// convert json objects to message objects
$list = [];
foreach ($response->objects() as $so) {
if (!$so instanceof MailParametersResponse) {
continue;
}
$id = $so->id();
$list[$id] = $so->parametersRaw();
$list[$id]['signature'] = $response->state();
}
// return message collection
return $list;
}
public function entityDownload(string $identifier, string|null $blobId = null): BinaryResource {
// construct request
$r0 = new MailGet($this->dataAccount, null, $this->resourceNamespace, $this->resourceEntityLabel);
$r0->target($identifier);
// select properties to return
$r0->property(...['id', 'blobId', 'bodyStructure']);
// transceive
$bundle = $this->dataStore->perform([$r0]);
// extract response
$response = $bundle->response(0);
$parameters = $response->object(0);
if (!$parameters instanceof MailParametersResponse) {
throw new Exception('Unexpected response type received from server.', 1);
}
if ($blobId === null) {
$blobId = $parameters->blob();
$filename = 'message.eml';
$mimeType = 'text/plain';
} else {
$walk = function (?MailPart $part) use (&$walk, $blobId): ?MailPart {
if ($part === null) {
return null;
}
if ($part->blob() === $blobId) {
return $part;
}
foreach ($part->parts() ?? [] as $subPart) {
$subPartResult = $walk($subPart);
if ($subPartResult !== null) {
return $subPartResult;
}
}
return null;
};
$part = $walk($parameters->bodyPartStructure());
$filename = $part->name() ?? 'file.bin';
$mimeType = $part->type() ?? 'application/octet-stream';
}
$streamResource = $this->dataStore->downloadStream($this->dataAccount, $blobId, $mimeType, $filename);
$stream = (function () use ($streamResource): \Generator {
try {
while (!$streamResource->eof()) {
$chunk = $streamResource->read(8192);
if ($chunk === '' && !$streamResource->eof()) {
throw new Exception('Unable to read from download stream.', 1);
}
if ($chunk !== '') {
yield $chunk;
}
}
} finally {
$streamResource->close();
}
})();
return new BinaryResource($filename, $mimeType, $stream);
}
/**
* check existence of entities in remote storage
*
@@ -718,8 +624,34 @@ class RemoteMailService {
return $delta;
}
public function entityFresh(): MailParametersRequest {
return new MailParametersRequest();
/**
* retrieve entity from remote storage
*
* @since Release 1.0.0
*/
public function entityFetch(string ...$identifiers): ?array {
// construct request
$r0 = new MailGet($this->dataAccount, null, $this->resourceNamespace, $this->resourceEntityLabel);
$r0->target(...$identifiers);
// select properties to return
$r0->property(...$this->defaultMailProperties);
$r0->bodyAll(true);
// transceive
$bundle = $this->dataStore->perform([$r0]);
// extract response
$response = $bundle->response(0);
// convert json objects to message objects
$list = [];
foreach ($response->objects() as $so) {
if (!$so instanceof MailParametersResponse) {
continue;
}
$id = $so->id();
$list[$id] = $so->parametersRaw();
$list[$id]['signature'] = $response->state();
}
// return message collection
return $list;
}
/**
@@ -792,37 +724,6 @@ class RemoteMailService {
return null;
}
public function entityPatch(MailParametersRequest $properties, string ...$identifiers): ?array {
// construct request
$r0 = new MailSet($this->dataAccount);
foreach ($identifiers as $id) {
$r0->patch($id, $properties);
}
// transceive
$bundle = $this->dataStore->perform([$r0]);
// extract response
$response = $bundle->first();
// 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);
}
}
$results = [];
// check for success
foreach ($response->updateSuccesses() as $id => $data) {
$results[$id] = true;
}
// check for failure
foreach ($response->updateFailures() as $id => $data) {
$results[$id] = $data['type'] ?? 'unknownError';
}
return $results;
}
/**
* delete entities from remote storage
*
@@ -860,6 +761,16 @@ class RemoteMailService {
return $results;
}
/**
* copy entity in remote storage
*
* @since Release 1.0.0
*
*/
public function entityCopy(string $target, string ...$identifiers): array {
return [];
}
/**
* move entity in remote storage
*
@@ -898,116 +809,99 @@ class RemoteMailService {
}
/**
* copy entity in remote storage
* send entity
*
* @since Release 1.0.0
*
*/
public function entityCopy(string $target, string ...$identifiers): array {
return [];
}
/**
* Submit a fresh message by creating it as a draft and then creating a submission.
*
* @since Release 2.0.0
*/
public function entitySubmitFresh(string $identityId, array $message, string $preSendTarget, string $postSentTarget): string {
$mail = new MailParametersRequest();
$mail->parametersRaw($message);
$messageCreateId = 'm_' . uniqid();
$submissionCreateId = 's_' . uniqid();
public function entitySend(string $identity, MailMessageObject $message, ?string $presendLocation = null, ?string $postsendLocation = null): string {
// determine if pre-send location is present
if ($presendLocation === null || empty($presendLocation)) {
throw new Exception('Pre-Send Location is missing', 1);
}
// determine if post-send location is present
if ($postsendLocation === null || empty($postsendLocation)) {
throw new Exception('Post-Send Location is missing', 1);
}
// determine if we have the basic required data and fail otherwise
if (empty($message->getFrom())) {
throw new Exception('Missing Requirements: Message MUST have a From address', 1);
}
if (empty($message->getTo())) {
throw new Exception('Missing Requirements: Message MUST have a To address(es)', 1);
}
// determine if message has attachments
if (count($message->getAttachments()) > 0) {
// process attachments first
$message = $this->depositAttachmentsFromMessage($message);
}
// convert from address object to string
$from = $message->getFrom()->getAddress();
// convert to, cc and bcc address object arrays to single strings array
$to = array_map(
function ($entry) { return $entry->getAddress(); },
array_merge($message->getTo(), $message->getCc(), $message->getBcc())
);
unset($cc, $bcc);
// construct set request
$r0 = new MailSet($this->dataAccount, null, $this->resourceNamespace, $this->resourceEntityLabel);
$createdMessage = $r0->create($messageCreateId, $mail);
$createdMessage->in($preSendTarget);
$r0->create('1', $message)->in($presendLocation);
// construct set request
$r1 = new MailSubmissionSet($this->dataAccount, null, $this->resourceNamespace, $this->resourceEntityLabel);
$submission = $r1->create($submissionCreateId);
$submission->identity($identityId);
$submission->message('#' . $messageCreateId);
// construct envelope
$e1 = $r1->create('2');
$e1->identity($identity);
$e1->message('#1');
$e1->from($from);
$e1->to($to);
// transceive
$bundle = $this->dataStore->perform([$r0, $r1]);
// extract response
$response = $bundle->response(1);
if ($response instanceof ResponseException) {
if ($response->type() === 'unknownMethod') {
throw new JmapUnknownMethod($response->description(), 1);
}
throw new Exception($response->type() . ': ' . $response->description(), 1);
}
return $this->extractSubmissionIdentifier($response, $submissionCreateId);
// return collection information
return (string)$response->created()['2']['id'];
}
/**
* Submit an existing draft message.
* retrieve collection entity attachment from remote storage
*
* @since Release 1.0.0
*
* @since Release 2.0.0
*/
public function entitySubmitDraft(string $identityId, string $draftId, ?array $patch = null): string {
if ($draftId === '') {
throw new Exception('Draft identifier is required for draft submission', 1);
}
public function depositAttachmentsFromMessage(MailMessageObject $message): MailMessageObject {
$requests = [];
$parameters = $message->toJmap();
$attachments = $message->getAttachments();
$matches = [];
if ($patch !== null && $patch !== []) {
$draftMutation = new MailParametersRequest();
$draftMutation->parametersRaw($patch);
$r0 = new MailSet($this->dataAccount, null, $this->resourceNamespace, $this->resourceEntityLabel);
$r0->update($draftId, $draftMutation);
$requests[] = $r0;
}
$this->findAttachmentParts($parameters['bodyStructure'], $matches);
$submissionCreateId = 's_' . uniqid();
$r1 = new MailSubmissionSet($this->dataAccount, null, $this->resourceNamespace, $this->resourceEntityLabel);
$submission = $r1->create($submissionCreateId);
$submission->identity($identityId);
$submission->message($draftId);
$requests[] = $r1;
$bundle = $this->dataStore->perform($requests);
$responseIndex = count($requests) - 1;
$response = $bundle->response($responseIndex);
if ($response instanceof ResponseException) {
if ($response->type() === 'unknownMethod') {
throw new JmapUnknownMethod($response->description(), 1);
foreach ($attachments as $attachment) {
$part = $attachment->toJmap();
if (isset($matches[$part->getId()])) {
// deposit attachment in data store
$response = $this->blobDeposit($account, $part->getType(), $attachment->getContents());
// transfer blobId and size to mail part
$matches[$part->getId()]->blobId = $response['blobId'];
$matches[$part->getId()]->size = $response['size'];
unset($matches[$part->getId()]->partId);
}
throw new Exception($response->type() . ': ' . $response->description(), 1);
}
return $this->extractSubmissionIdentifier($response, $submissionCreateId);
return (new MailMessageObject())->fromJmap($parameters);
}
private function collectionByRole(string $role): ?string {
$filter = $this->collectionListFilter();
$filter->condition('role', $role);
protected function findAttachmentParts(object &$part, array &$matches) {
$collections = $this->collectionList(null, $filter, null);
if ($collections === []) {
return null;
if ($part->disposition === 'attachment' || $part->disposition === 'inline') {
$matches[$part->partId] = $part;
}
return (string)array_key_first($collections);
}
private function extractSubmissionIdentifier(object $response, string $createId): string {
if (method_exists($response, 'createSuccess')) {
$success = $response->createSuccess($createId);
if (is_array($success) && isset($success['id'])) {
return (string)$success['id'];
}
foreach ($part->subParts as $entry) {
$this->findAttachmentParts($entry, $matches);
}
if (method_exists($response, 'created')) {
$created = $response->created();
if (is_array($created) && isset($created[$createId]['id'])) {
return (string)$created[$createId]['id'];
}
}
throw new Exception('Submission succeeded without a returned identifier', 1);
}
/**
+10 -14
View File
@@ -9,12 +9,16 @@ declare(strict_types=1);
namespace KTXM\ProviderJmapc\Service\Remote;
use GuzzleHttp\Client as HttpClient;
use GuzzleHttp\Psr7\HttpFactory;
use JmapClient\Authentication\Basic;
use JmapClient\Authentication\Bearer;
use JmapClient\Authentication\JsonBasic;
use JmapClient\Authentication\JsonBasicCookie;
use JmapClient\Client as JmapClient;
use KTXC\Server;
use KTXF\Resource\Provider\ResourceServiceBaseInterface;
use KTXF\Resource\Provider\ResourceServiceIdentityBasic;
use KTXF\Resource\Provider\ResourceServiceIdentityBearer;
use KTXF\Resource\Provider\ResourceServiceIdentityOAuth;
use KTXF\Resource\Provider\ResourceServiceLocationUri;
use KTXM\ProviderJmapc\Providers\Mail\Service as MailService;
use KTXM\ProviderJmapc\Providers\Contacts\Service as ContactsService;
@@ -36,6 +40,9 @@ class RemoteService {
*/
public static function freshClient(MailService|FilesService $service): JmapClient {
// defaults
$client = new JmapClient();
$client->setTransportAgent(self::$clientTransportAgent);
$location = $service->getLocation();
$identity = $service->getIdentity();
@@ -43,23 +50,12 @@ class RemoteService {
if ($location instanceof ResourceServiceLocationUri === false) {
throw new \InvalidArgumentException('Service location is not a valid URI');
}
// The JMAP client accepts transport abstractions only. Guzzle supplies the
// PSR-18 client, while HttpFactory supplies both required PSR-17 factories.
$httpFactory = new HttpFactory();
$client = new JmapClient(
transportClient: new HttpClient([
'verify' => $location->getVerifyPeer(),
]),
requestFactory: $httpFactory,
streamFactory: $httpFactory,
);
$client->setTransportAgent(self::$clientTransportAgent);
$client->configureTransportMode($location->getScheme());
$client->setHost($location->getHost() . ':' . $location->getPort());
if (!empty($location->getPath())) {
$client->setDiscoveryPath($location->getPath());
}
$client->configureTransportVerification((bool)$location->getVerifyPeer());
// authentication
if (($identity instanceof ResourceServiceIdentityBasic) === false) {
throw new \InvalidArgumentException('Service identity is not a valid Basic or Bearer authentication');
+1222 -1761
View File
File diff suppressed because it is too large Load Diff
+2 -5
View File
@@ -27,12 +27,9 @@
"@vitejs/plugin-vue": "^6.0.1",
"@vitest/coverage-v8": "^4.0.18",
"@vitest/ui": "^4.0.18",
"@vue/test-utils": "^2.4.10",
"@vue/tsconfig": "^0.9.0",
"jsdom": "^29.1.1",
"typescript": "~6.0.0",
"vite": "^8.0.0",
"vitest": "^4.0.18",
"typescript": "~5.8.3",
"vite": "^7.1.2",
"vue-tsc": "^3.0.5"
}
}
+40 -97
View File
@@ -1,7 +1,6 @@
<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { ServiceObject } from '@KTXM/MailManager/models/service'
import { ServiceAddressObject } from '@KTXM/MailManager/models/address'
type AuxiliaryTab = 'addresses' | 'messages' | 'sync'
type DeleteMode = 'soft' | 'hard'
@@ -17,8 +16,8 @@ const emit = defineEmits<{
const activeTab = ref<AuxiliaryTab>('addresses')
const deleteMode = ref<DeleteMode>('soft')
const deleteDestination = ref('Trash')
const primaryAddress = ref<ServiceAddressObject>(new ServiceAddressObject())
const secondaryAddresses = ref<ServiceAddressObject[]>([])
const primaryAddress = ref('')
const secondaryAddresses = ref('')
const settingGroups = [
{
@@ -62,6 +61,10 @@ const destinationHint = computed(() => {
return 'Mailbox identifier or well-known role target, for example Trash.'
})
const secondaryAddressesHint = computed(() => {
return 'Use one address per line. Commas are also accepted.'
})
watch(
() => props.service,
service => {
@@ -83,17 +86,17 @@ watch(
}
if (sameAuxiliary(nextService.auxiliary ?? {}, nextAuxiliary)) {
if (sameAddresses(nextService)) {
if (sameAddresses(nextService, primaryAddress.value, secondaryAddresses.value)) {
return
}
}
nextService.primaryAddress = primaryAddress.value.empty ? null : primaryAddress.value
nextService.secondaryAddresses = dedupeAddresses(secondaryAddresses.value)
nextService.primaryAddress = normalizePrimaryAddress(primaryAddress.value)
nextService.secondaryAddresses = normalizeSecondaryAddresses(secondaryAddresses.value)
nextService.auxiliary = nextAuxiliary
emit('update:service', nextService)
},
{ deep: true, immediate: true }
{ immediate: true }
)
function syncFromService(service?: ServiceObject) {
@@ -102,8 +105,8 @@ function syncFromService(service?: ServiceObject) {
deleteDestination.value = typeof auxiliary.deleteDestination === 'string' && auxiliary.deleteDestination.length > 0
? auxiliary.deleteDestination
: 'Trash'
primaryAddress.value = service?.primaryAddress ?? new ServiceAddressObject()
secondaryAddresses.value = service?.secondaryAddresses ?? []
primaryAddress.value = service?.primaryAddress ?? ''
secondaryAddresses.value = (service?.secondaryAddresses ?? []).join('\n')
}
function normalizeDeleteDestination(value: string): string {
@@ -111,23 +114,16 @@ 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 {
function normalizePrimaryAddress(value: string): string | null {
const trimmedValue = value.trim()
return trimmedValue.length === 0 || /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(trimmedValue) || 'Invalid email address'
return trimmedValue.length > 0 ? trimmedValue : null
}
function normalizeSecondaryAddresses(value: string): string[] {
return value
.split(/\r?\n|,/)
.map(entry => entry.trim())
.filter((entry, index, entries) => entry.length > 0 && entries.indexOf(entry) === index)
}
function sameAuxiliary(current: Record<string, any>, next: Record<string, any>): boolean {
@@ -135,19 +131,9 @@ function sameAuxiliary(current: Record<string, any>, next: Record<string, any>):
&& (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)
function sameAddresses(service: ServiceObject, nextPrimaryAddress: string, nextSecondaryAddresses: string): boolean {
return (service.primaryAddress ?? null) === normalizePrimaryAddress(nextPrimaryAddress)
&& JSON.stringify(service.secondaryAddresses) === JSON.stringify(normalizeSecondaryAddresses(nextSecondaryAddresses))
}
</script>
@@ -179,66 +165,23 @@ function sameAddress(current: ServiceAddressObject | null, next: ServiceAddressO
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
v-model="primaryAddress.label"
label="Display Name"
variant="outlined"
density="compact"
hide-details="auto"
/>
<v-text-field
v-model="primaryAddress.address"
label="Email Address"
variant="outlined"
density="compact"
prepend-inner-icon="mdi-email-outline"
:rules="[validAddress]"
hide-details="auto"
/>
</div>
<v-text-field
v-model="primaryAddress"
label="Primary Address"
variant="outlined"
prepend-inner-icon="mdi-email-outline"
class="mb-4"
/>
<div class="text-subtitle-2 mb-2">Secondary Addresses</div>
<div
v-for="(entry, index) in secondaryAddresses"
:key="index"
class="d-flex ga-2 mb-2"
>
<v-text-field
v-model="entry.label"
label="Display Name"
variant="outlined"
density="compact"
hide-details="auto"
/>
<v-text-field
v-model="entry.address"
label="Email Address"
variant="outlined"
density="compact"
prepend-inner-icon="mdi-email-multiple-outline"
:rules="[validAddress]"
hide-details="auto"
/>
<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>
<v-textarea
v-model="secondaryAddresses"
label="Secondary Addresses"
variant="outlined"
prepend-inner-icon="mdi-email-multiple-outline"
rows="4"
:hint="secondaryAddressesHint"
persistent-hint
/>
</div>
</v-window-item>
+3 -3
View File
@@ -1,17 +1,17 @@
import { fileURLToPath } from 'node:url'
import { defineConfig, configDefaults } from 'vitest/config'
import vue from '@vitejs/plugin-vue'
import vuetify from 'vite-plugin-vuetify'
import path from 'path'
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
export default defineConfig({
plugins: [vue()],
plugins: [vue(), vuetify()],
resolve: {
alias: {
'@': path.resolve(__dirname, '../../src'),
'@KTXC': path.resolve(__dirname, '../../../../core/src'),
'@KTXC': path.resolve(__dirname, '../../../core/src'),
},
},
test: {
-29
View File
@@ -1,29 +0,0 @@
<?php
namespace KTXT\ProviderJmapc\Integration;
use PHPUnit\Framework\TestCase;
class BaseTest extends TestCase
{
public function testBasicAssertion(): void
{
$this->assertTrue(true);
}
public function testArrayOperations(): void
{
$array = ['foo' => 'bar'];
$this->assertArrayHasKey('foo', $array);
$this->assertEquals('bar', $array['foo']);
}
public function testStringOperations(): void
{
$string = 'Hello, World!';
$this->assertStringContainsString('World', $string);
$this->assertEquals(13, strlen($string));
}
}
-10
View File
@@ -2,16 +2,6 @@
require dirname(__DIR__, 2).'/lib/vendor/autoload.php';
// When this module is checked out inside a full server (server/modules/<handle>,
// as it is in CI and in this monorepo checkout), also load the server's own
// core/shared autoloader so tests can reference framework (KTXC/KTXF) types.
// Standalone module checkouts without a server alongside them skip this.
define('SERVER_ROOT', dirname(__DIR__, 4));
$serverAutoload = SERVER_ROOT . '/vendor/autoload.php';
if (is_file($serverAutoload)) {
require $serverAutoload;
}
if (isset($_SERVER['APP_DEBUG']) && $_SERVER['APP_DEBUG']) {
umask(0000);
}
@@ -21,9 +21,6 @@
<testsuite name="Unit Tests">
<directory>unit</directory>
</testsuite>
<testsuite name="Integration Tests">
<directory>Integration</directory>
</testsuite>
</testsuites>
<source ignoreSuppressionOfDeprecations="true"
@@ -32,7 +29,8 @@
restrictWarnings="true"
>
<include>
<directory>../../lib</directory>
<directory>../../core/lib</directory>
<directory>../../shared/lib</directory>
</include>
<deprecationTrigger>