|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | + * This file is part of the Symfony package. |
| 5 | + * |
| 6 | + * (c) Fabien Potencier <fabien@symfony.com> |
| 7 | + * |
| 8 | + * For the full copyright and license information, please view the LICENSE |
| 9 | + * file that was distributed with this source code. |
| 10 | + */ |
| 11 | + |
| 12 | +namespace Symfony\Component\Notifier\Bridge\Matrix; |
| 13 | + |
| 14 | +use Symfony\Component\Notifier\Exception\LogicException; |
| 15 | +use Symfony\Component\Notifier\Exception\TransportException; |
| 16 | +use Symfony\Component\Notifier\Exception\UnsupportedMessageTypeException; |
| 17 | +use Symfony\Component\Notifier\Exception\UnsupportedOptionsException; |
| 18 | +use Symfony\Component\Notifier\Message\ChatMessage; |
| 19 | +use Symfony\Component\Notifier\Message\MessageInterface; |
| 20 | +use Symfony\Component\Notifier\Message\SentMessage; |
| 21 | +use Symfony\Component\Notifier\Transport\AbstractTransport; |
| 22 | +use Symfony\Component\Uid\Uuid; |
| 23 | +use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; |
| 24 | +use Symfony\Contracts\HttpClient\HttpClientInterface; |
| 25 | +use Symfony\Contracts\HttpClient\ResponseInterface; |
| 26 | + |
| 27 | +/** |
| 28 | + * @author Frank Schulze <frank@akiber.de> |
| 29 | + */ |
| 30 | +final class MatrixTransport extends AbstractTransport |
| 31 | +{ |
| 32 | + // not all Message Types are supported by Matrix API |
| 33 | + private const SUPPORTED_MSG_TYPES_BY_API = ['m.text', 'm.emote', 'm.notice', 'm.image', 'm.file', 'm.audio', 'm.video', 'm.key.verification']; |
| 34 | + |
| 35 | + public function __construct( |
| 36 | + #[\SensitiveParameter] private string $accessToken, |
| 37 | + private bool $ssl, |
| 38 | + ?HttpClientInterface $client = null, |
| 39 | + ?EventDispatcherInterface $dispatcher = null, |
| 40 | + ) { |
| 41 | + parent::__construct($client, $dispatcher); |
| 42 | + } |
| 43 | + |
| 44 | + public function __toString(): string |
| 45 | + { |
| 46 | + return \sprintf('matrix://%s', $this->getEndpoint(false)); |
| 47 | + } |
| 48 | + |
| 49 | + public function supports(MessageInterface $message): bool |
| 50 | + { |
| 51 | + return $message instanceof ChatMessage && (null === $message->getOptions() || $message->getOptions() instanceof MatrixOptions); |
| 52 | + } |
| 53 | + |
| 54 | + protected function doSend(MessageInterface $message): SentMessage |
| 55 | + { |
| 56 | + if (!$message instanceof ChatMessage) { |
| 57 | + throw new UnsupportedMessageTypeException(__CLASS__, ChatMessage::class, $message); |
| 58 | + } |
| 59 | + |
| 60 | + if (($opts = $message->getOptions()) && !$message->getOptions() instanceof MatrixOptions) { |
| 61 | + throw new UnsupportedOptionsException(__CLASS__, MatrixOptions::class, $opts); |
| 62 | + } |
| 63 | + |
| 64 | + $options = $opts ? $opts->toArray() : []; |
| 65 | + |
| 66 | + $options['msgtype'] = $options['msgtype'] ?? 'm.text'; |
| 67 | + |
| 68 | + if (!\in_array($options['msgtype'], self::SUPPORTED_MSG_TYPES_BY_API, true)) { |
| 69 | + 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))); |
| 70 | + } |
| 71 | + |
| 72 | + if (null === $message->getRecipientId()) { |
| 73 | + throw new LogicException('Recipient id is required.'); |
| 74 | + } |
| 75 | + |
| 76 | + $recipient = match ($message->getRecipientId()[0]) { |
| 77 | + '@' => $this->getDirectMessageChannel($message->getRecipientId()), |
| 78 | + '!' => $message->getRecipientId(), |
| 79 | + '#' => $this->getRoomFromAlias($message->getRecipientId()), |
| 80 | + default => throw new LogicException(\sprintf('Only recipients starting with "!","@","#" are supported ("%s" given).', $message->getRecipientId()[0])), |
| 81 | + }; |
| 82 | + |
| 83 | + $options['body'] = $message->getSubject(); |
| 84 | + if ('org.matrix.custom.html' === $options['format']) { |
| 85 | + $options['formatted_body'] = $message->getSubject();
10000
|
| 86 | + $options['body'] = strip_tags($message->getSubject()); |
| 87 | + } |
| 88 | + |
| 89 | + $response = $this->request('PUT', \sprintf('/_matrix/client/v3/rooms/%s/send/%s/%s', $recipient, 'm.room.message', Uuid::v4()), ['json' => $options]); |
| 90 | + |
| 91 | + $success = $response->toArray(false); |
| 92 | + $sentMessage = new SentMessage($message, (string) $this); |
| 93 | + $sentMessage->setMessageId($success['event_id']); |
| 94 | + |
| 95 | + return $sentMessage; |
| 96 | + } |
| 97 | + |
| 98 | + protected function getEndpoint(bool $full = false): string |
| 99 | + { |
| 100 | + return rtrim(($full ? $this->getScheme().'://' : '').$this->host.($this->port ? ':'.$this->port : ''), '/'); |
| 101 | + } |
| 102 | + |
| 103 | + private function getRoomFromAlias(string $alias): string |
| 104 | + { |
| 105 | + $response = $this->request('GET', \sprintf('/_matrix/client/v3/directory/room/%s', urlencode($alias))); |
| 106 | + |
| 107 | + return $response->toArray()['room_id']; |
| 108 | + } |
| 109 | + |
| 110 | + private function createPrivateChannel(string $recipientId): ?array |
| 111 | + { |
| 112 | + $invites[] = $recipientId; |
| 113 | + $response = $this->request('POST', '/_matrix/client/v3/createRoom', ['json' => ['creation_content' => ['m.federate' => false], 'is_direct' => true, 'preset' => 'trusted_private_chat', 'invite' => $invites]]); |
| 114 | + |
| 115 | + return $response->toArray(); |
| 116 | + } |
| 117 | + |
| 118 | + private function getDirectMessageChannel(string $recipientId): ?string |
| 119 | + { |
| 120 | + $response = $this->getAccountData($this->getWhoami()['user_id'], 'm.direct'); |
| 121 | + if (!isset($response[$recipientId])) { |
| 122 | + $roomid = $this->createPrivateChannel($recipientId)['room_id']; |
| 123 | + $response[$recipientId] = [$roomid]; |
| 124 | + $this->updateAccountData($this->getWhoami()['user_id'], 'm.direct', $response); |
| 125 | + |
| 126 | + return $roomid; |
| 127 | + } |
| 128 | + |
| 129 | + return $response[$recipientId][0]; |
| 130 | + } |
| 131 | + |
| 132 | + private function updateAccountData(string $userId, string $type, array $data): void |
| 133 | + { |
| 134 | + $response = $this->request('PUT', \sprintf('/_matrix/client/v3/user/%s/account_data/%s', urlencode($userId), $type), ['json' => $data]); |
| 135 | + if ([] !== $response->toArray()) { |
| 136 | + throw new TransportException('Unable to update account data.', $response); |
| 137 | + } |
| 138 | + } |
| 139 | + |
| 140 | + private function getAccountData(string $userId, string $type): ?array |
| 141 | + { |
| 142 | + $response = $this->request('GET', \sprintf('/_matrix/client/v3/user/%s/account_data/%s', urlencode($userId), $type)); |
| 143 | + |
| 144 | + return $response->toArray(); |
| 145 | + } |
| 146 | + |
| 147 | + private function getWhoami(): ?array |
| 148 | + { |
| 149 | + $response = $this->request('GET', '/_matrix/client/v3/account/whoami'); |
| 150 | + |
| 151 | + return $response->toArray(); |
| 152 | + } |
| 153 | + |
| 154 | + private function getScheme(): string |
| 155 | + { |
| 156 | + return $this->ssl ? 'https' : 'http'; |
| 157 | + } |
| 158 | + |
| 159 | + private function request(string $method, string $uri, ?array $options = []): ResponseInterface |
| 160 | + { |
| 161 | + $options += [ |
| 162 | + 'auth_bearer' => $this->accessToken, |
| 163 | + ]; |
| 164 | + $response = $this->client->request($method, $this->getEndpoint(true).$uri, $options); |
| 165 | + |
| 166 | + try { |
| 167 | + $statusCode = $response->getStatusCode(); |
| 168 | + } catch (TransportException $e) { |
| 169 | + throw new TransportException('Could not reach the Matrix server.', $response, 0, $e); |
| 170 | + } |
| 171 | + |
| 172 | + if (\in_array($statusCode, [400, 403, 405])) { |
| 173 | + $result = $response->toArray(false); |
| 174 | + throw new TransportException(\sprintf('Error: Matrix responded with "%s (%s)"', $result['error'], $result['errcode']), $response); |
| 175 | + } |
| 176 | + |
| 177 | + return $response; |
| 178 | + } |
| 179 | +} |
0 commit comments