-
-
Notifications
You must be signed in to change notification settings - Fork 9.6k
[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
[Notifier] Add Matrix bridge #59377
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
vendor/ | ||
composer.lock | ||
phpunit.xml |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
CHANGELOG | ||
========= | ||
|
||
7.3 | ||
--- | ||
|
||
* Add the bridge |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
40
src/Symfony/Component/Notifier/Bridge/Matrix/MatrixOptions.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
179
src/Symfony/Component/Notifier/Bridge/Matrix/MatrixTransport.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
chii0815 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
|
||
protected function doSend(MessageInterface $message): SentMessage | ||
chii0815 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
{ | ||
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]]); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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; | ||
} | ||
} |
41 changes: 41 additions & 0 deletions
41
src/Symfony/Component/Notifier/Bridge/Matrix/MatrixTransportFactory.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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']; | ||
} | ||
} |
chii0815 marked this conversation as resolved.
Show resolved
Hide resolved
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
Matrix Notifier | ||
=============== | ||
|
||
Provides [Matrix](https://matrix.org) integration 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/) |
46 changes: 46 additions & 0 deletions
46
src/Symfony/Component/Notifier/Bridge/Matrix/Tests/MatrixOptionsTest.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | ||
chii0815 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
{ | ||
$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()); | ||
} | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.