8000 [Notifier] Add Matrix bridge by chii0815 · Pull Request #59377 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

[Notifier] Add Matrix bridge #59377

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 14, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2926,6 +2926,7 @@ private function registerNotifierConfiguration(array $config, ContainerBuilder $
NotifierBridge\Lox24\Lox24TransportFactory::class => 'notifier.transport_factory.lox24',
NotifierBridge\Mailjet\MailjetTransportFactory::class => 'notifier.transport_factory.mailjet',
NotifierBridge\Mastodon\MastodonTransportFactory::class => 'notifier.transport_factory.mastodon',
NotifierBridge\Matrix\MatrixTransportFactory::class => 'notifier.transport_factory.matrix',
NotifierBridge\Mattermost\MattermostTransportFactory::class => 'notifier.transport_factory.mattermost',
NotifierBridge\Mercure\MercureTransportFactory::class => 'notifier.transport_factory.mercure',
NotifierBridge\MessageBird\MessageBirdTransportFactory::class => 'notifier.transport_factory.message-bird',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
'line-notify' => Bridge\LineNotify\LineNotifyTransportFactory::class,
'linked-in' => Bridge\LinkedIn\LinkedInTransportFactory::class,
'mastodon' => Bridge\Mastodon\MastodonTransportFactory::class,
'matrix' => Bridge\Matrix\MatrixTransportFactory::class,
'mattermost' => Bridge\Mattermost\MattermostTransportFactory::class,
'mercure' => Bridge\Mercure\MercureTransportFactory::class,
'microsoft-teams' => Bridge\MicrosoftTeams\MicrosoftTeamsTransportFactory::class,
Expand Down
3 changes: 3 additions & 0 deletions src/Symfony/Component/Notifier/Bridge/Matrix/.gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
/Tests export-ignore
/phpunit.xml.dist export-ignore
/.git* export-ignore
3 changes: 3 additions & 0 deletions src/Symfony/Component/Notifier/Bridge/Matrix/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
vendor/
composer.lock
phpunit.xml
7 changes: 7 additions & 0 deletions src/Symfony/Component/Notifier/Bridge/Matrix/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
CHANGELOG
=========

7.3
---

* Add the bridge
19 changes: 19 additions & 0 deletions src/Symfony/Component/Notifier/Bridge/Matrix/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
Copyright (c) 2025-present Fabien Potencier

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
40 changes: 40 additions & 0 deletions src/Symfony/Component/Notifier/Bridge/Matrix/MatrixOptions.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Notifier\Bridge\Matrix;

use Symfony\Component\Notifier\Message\MessageOptionsInterface;

/**
* @author Frank Schulze <frank@akiber.de>
*/
final class MatrixOptions implements MessageOptionsInterface, \JsonSerializable
{
public function __construct(
private array $options = [],
) {
}

public function toArray(): array
{
return $this->options;
}

public function getRecipientId(): ?string
{
return $this->options['recipient_id'] ?? null;
}

public function jsonSerialize(): mixed
{
return $this->options;
}
}
179 changes: 179 additions & 0 deletions src/Symfony/Component/Notifier/Bridge/Matrix/MatrixTransport.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Notifier\Bridge\Matrix;

use Symfony\Component\Notifier\Exception\LogicException;
use Symfony\Component\Notifier\Exception\TransportException;
use Symfony\Component\Notifier\Exception\UnsupportedMessageTypeException;
use Symfony\Component\Notifier\Exception\UnsupportedOptionsException;
use Symfony\Component\Notifier\Message\ChatMessage;
use Symfony\Component\Notifier\Message\MessageInterface;
use Symfony\Component\Notifier\Message\SentMessage;
use Symfony\Component\Notifier\Transport\AbstractTransport;
use Symfony\Component\Uid\Uuid;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\HttpClient\ResponseInterface;

/**
* @author Frank Schulze <frank@akiber.de>
*/
final class MatrixTransport extends AbstractTransport
{
// not all Message Types are supported by Matrix API
private const SUPPORTED_MSG_TYPES_BY_API = ['m.text', 'm.emote', 'm.notice', 'm.image', 'm.file', 'm.audio', 'm.video', 'm.key.verification'];

public function __construct(
#[\SensitiveParameter] private string $accessToken,
private bool $ssl,
?HttpClientInterface $client = null,
?EventDispatcherInterface $dispatcher = null,
) {
parent::__construct($client, $dispatcher);
}

public function __toString(): string
{
return \sprintf('matrix://%s', $this->getEndpoint(false));
}

public function supports(MessageInterface $message): bool
{
return $message instanceof ChatMessage && (null === $message->getOptions() || $message->getOptions() instanceof MatrixOptions);
}

protected function doSend(MessageInterface $message): SentMessage
{
if (!$message instanceof ChatMessage) {
throw new UnsupportedMessageTypeException(__CLASS__, ChatMessage::class, $message);
}

if (($opts = $message->getOptions()) && !$message->getOptions() instanceof MatrixOptions) {
throw new UnsupportedOptionsException(__CLASS__, MatrixOptions::class, $opts);
}

$options = $opts ? $opts->toArray() : [];

$options['msgtype'] = $options['msgtype'] ?? 'm.text';

if (!\in_array($options['msgtype'], self::SUPPORTED_MSG_TYPES_BY_API, true)) {
throw new LogicException(\sprintf('Unsupported message type: "%s". Only "%s" are supported by Matrix Client-Server API v3.', $options['msgtype'], implode(', ', self::SUPPORTED_MSG_TYPES_BY_API)));
}

if (null === $message->getRecipientId()) {
throw new LogicException('Recipient id is required.');
}

$recipient = match ($message->getRecipientId()[0]) {
'@' => $this->getDirectMessageChannel($message->getRecipientId()),
'!' => $message->getRecipientId(),
'#' => $this->getRoomFromAlias($message->getRecipientId()),
default => throw new LogicException(\sprintf('Only recipients starting with "!","@","#" are supported ("%s" given).', $message->getRecipientId()[0])),
};

$options['body'] = $message->getSubject();
if ('org.matrix.custom.html' === $options['format']) {
$options['formatted_body'] = $message->getSubject();
$options['body'] = strip_tags($message->getSubject());
}

$response = $this->request('PUT', \sprintf('/_matrix/client/v3/rooms/%s/send/%s/%s', $recipient, 'm.room.message', Uuid::v4()), ['json' => $options]);

$success = $response->toArray(false);
$sentMessage = new SentMessage($message, (string) $this);
$sentMessage->setMessageId($success['event_id']);

return $sentMessage;
}

protected function getEndpoint(bool $full = false): string
{
return rtrim(($full ? $this->getScheme().'://' : '').$this->host.($this->port ? ':'.$this->port : ''), '/');
}

private function getRoomFromAlias(string $alias): string
{
$response = $this->request('GET', \sprintf('/_matrix/client/v3/directory/room/%s', urlencode($alias)));

return $response->toArray()['room_id'];
}

private function createPrivateChannel(string $recipientId): ?array
{
$invites[] = $recipientId;
$response = $this->request('POST', '/_matrix/client/v3/createRoom', ['json' => ['creation_content' => ['m.federate' => false], 'is_direct' => true, 'preset' => 'trusted_private_chat', 'invite' => $invites]]);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

using multiline here makes sense to me, no need for a one liner in this case


return $response->toArray();
}

private function getDirectMessageChannel(string $recipientId): ?string
{
$response = $this->getAccountData($this->getWhoami()['user_id'], 'm.direct');
if (!isset($response[$recipientId])) {
$roomid = $this->createPrivateChannel($recipientId)['room_id'];
$response[$recipientId] = [$roomid];
$this->updateAccountData($this->getWhoami()['user_id'], 'm.direct', $response);

return $roomid;
}

return $response[$recipientId][0];
}

private function updateAccountData(string $userId, string $type, array $data): void
{
$response = $this->request('PUT', \sprintf('/_matrix/client/v3/user/%s/account_data/%s', urlencode($userId), $type), ['json' => $data]);
if ([] !== $response->toArray()) {
throw new TransportException('Unable to update account data.', $response);
}
}

private function getAccountData(string $userId, string $type): ?array
{
$response = $this->request('GET', \sprintf('/_matrix/client/v3/user/%s/account_data/%s', urlencode($userId), $type));

return $response->toArray();
}

private function getWhoami(): ?array
{
$response = $this->request('GET', '/_matrix/client/v3/account/whoami');

return $response->toArray();
}

private function getScheme(): string
{
return $this->ssl ? 'https' : 'http';
}

private function request(string $method, string $uri, ?array $options = []): ResponseInterface
{
$options += [
'auth_bearer' => $this->accessToken,
];
$response = $this->client->request($method, $this->getEndpoint(true).$uri, $options);

try {
$statusCode = $response->getStatusCode();
} catch (TransportException $e) {
throw new TransportException('Could not reach the Matrix server.', $response, 0, $e);
}

if (\in_array($statusCode, [400, 403, 405])) {
$result = $response->toArray(false);
throw new TransportException(\sprintf('Error: Matrix responded with "%s (%s)"', $result['error'], $result['errcode']), $response);
}

return $response;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Notifier\Bridge\Matrix;

use Symfony\Component\Notifier\Exception\UnsupportedSchemeException;
use Symfony\Component\Notifier\Transport\AbstractTransportFactory;
use Symfony\Component\Notifier\Transport\Dsn;

/**
* @author Frank Schulze <frank@akiber.de>
*/
class MatrixTransportFactory extends AbstractTransportFactory
{
public function create(Dsn $dsn): MatrixTransport
{
if ('matrix' !== $dsn->getScheme()) {
throw new UnsupportedSchemeException($dsn, 'matrix', $this->getSupportedSchemes());
}

$token = $dsn->getRequiredOption('accessToken');
$host = $dsn->getHost();
$port = $dsn->getPort();
$ssl = $dsn->getBooleanOption('ssl', true);

return (new MatrixTransport($token, $ssl, $this->client, $this->dispatcher))->setHost($host)->setPort($port);
}

protected function getSupportedSchemes(): array
{
return ['matrix'];
}
}
29 changes: 29 additions & 0 deletions src/Symfony/Component/Notifier/Bridge/Matrix/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
Matrix Notifier
===============

Provides [Matrix](https://matrix.org) integr F42D ation for Symfony Notifier.
It uses the [Matrix Client-Server API](https://spec.matrix.org/v1.13/client-server-api/).

```
Note:
This Bridge was tested with the official Matrix Synapse Server and the Client-Server API v3 (version v1.13).
But it should work with every Matrix Client-Server API v3 compliant homeserver.
```

DSN example
-----------

```
MATRIX_DSN=matrix://HOST:PORT/?accessToken=ACCESS_TOKEN&ssl=true
```
To get started you need an access token. The simplest way to get that is to open Element in a private (incognito) window in your webbrowser or just use your currently open Element. Go to Settings > Help & About > Advanced > Access Token `click to reveal` and copy your access token.

Resources
---------

* [Contributing](https://symfony.com/doc/current/contributing/index.html)
* [Report issues](https://github.com/symfony/symfony/issues) and
[send Pull Requests](https://github.com/symfony/symfony/pulls)
in the [main Symfony repository](https://github.com/symfony/symfony)
* [Matrix Playground](https://playground.matrix.org)
* [Matrix Client-Server API](https://spec.matrix.org/latest/client-server-api/)
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Notifier\Bridge\Matrix\Tests;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Notifier\Bridge\Matrix\MatrixOptions;

class MatrixOptionsTest extends TestCase
{
public function testToArray()
{
$options = new MatrixOptions([
'recipient_id' => '@testuser:matrix.io',
'msgtype' => 'm.text',
'format' => 'org.matrix.custom.html',
]);
$this->assertSame(['recipient_id' => '@testuser:matrix.io', 'msgtype' => 'm.text', 'format' => 'org.matrix.custom.html'], $options->toArray());
}

public function testGetRecipientId()
{
$options = new MatrixOptions([
'recipient_id' => '@testuser:matrix.io',
]);
$this->assertSame('@testuser:matrix.io', $options->getRecipientId());
}

public function testJsonSerialize()
{
$options = new MatrixOptions([
'recipient_id' => '@testuser:matrix.io',
'msgtype' => 'm.text',
'format' => 'org.matrix.custom.html',
]);
$this->assertSame(['recipient_id' => '@testuser:matrix.io', 'msgtype' => 'm.text', 'format' => 'org.matrix.custom.html'], $options->jsonSerialize());
}
}
Loading
Loading
0