Skip to content

Commit

Permalink
feature #48101 [Notifier] Add Mastodon Notifier (qdequippe)
Browse files Browse the repository at this point in the history
This PR was merged into the 6.3 branch.

Discussion
----------

[Notifier] Add Mastodon Notifier

| Q             | A
| ------------- | ---
| Branch?       | 6.3
| Bug fix?      | no
| New feature?  | yes
| Deprecations? | no
| Tickets       |
| License       | MIT
| Doc PR        | symfony/symfony-docs#17411
| Recipe        | symfony/recipes#1141

Migrate from Twitter with this new Symfony Notifier Bridge for Mastodon :)

Commits
-------

d097a63 Add Mastodon Notifier
  • Loading branch information
nicolas-grekas committed Dec 5, 2022
2 parents 309b10a + d097a63 commit aee9ea5
Show file tree
Hide file tree
Showing 19 changed files with 565 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,7 @@
use Symfony\Component\Notifier\Bridge\LineNotify\LineNotifyTransportFactory;
use Symfony\Component\Notifier\Bridge\LinkedIn\LinkedInTransportFactory;
use Symfony\Component\Notifier\Bridge\Mailjet\MailjetTransportFactory as MailjetNotifierTransportFactory;
use Symfony\Component\Notifier\Bridge\Mastodon\MastodonTransportFactory;
use Symfony\Component\Notifier\Bridge\Mattermost\MattermostTransportFactory;
use Symfony\Component\Notifier\Bridge\Mercure\MercureTransportFactory;
use Symfony\Component\Notifier\Bridge\MessageBird\MessageBirdTransport;
Expand Down Expand Up @@ -2580,6 +2581,7 @@ private function registerNotifierConfiguration(array $config, ContainerBuilder $
LineNotifyTransportFactory::class => 'notifier.transport_factory.line-notify',
LinkedInTransportFactory::class => 'notifier.transport_factory.linked-in',
MailjetNotifierTransportFactory::class => 'notifier.transport_factory.mailjet',
MastodonTransportFactory::class => 'notifier.transport_factory.mastodon',
MattermostTransportFactory::class => 'notifier.transport_factory.mattermost',
MercureTransportFactory::class => 'notifier.transport_factory.mercure',
MessageBirdTransport::class => 'notifier.transport_factory.message-bird',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
use Symfony\Component\Notifier\Bridge\LineNotify\LineNotifyTransportFactory;
use Symfony\Component\Notifier\Bridge\LinkedIn\LinkedInTransportFactory;
use Symfony\Component\Notifier\Bridge\Mailjet\MailjetTransportFactory;
use Symfony\Component\Notifier\Bridge\Mastodon\MastodonTransportFactory;
use Symfony\Component\Notifier\Bridge\Mattermost\MattermostTransportFactory;
use Symfony\Component\Notifier\Bridge\Mercure\MercureTransportFactory;
use Symfony\Component\Notifier\Bridge\MessageBird\MessageBirdTransportFactory;
Expand Down Expand Up @@ -321,5 +322,9 @@
->set('notifier.transport_factory.line-notify', LineNotifyTransportFactory::class)
->parent('notifier.transport_factory.abstract')
->tag('chatter.transport_factory')

->set('notifier.transport_factory.mastodon', MastodonTransportFactory::class)
->parent('notifier.transport_factory.abstract')
->tag('chatter.transport_factory')
;
};
4 changes: 4 additions & 0 deletions src/Symfony/Component/Notifier/Bridge/Mastodon/.gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/Tests export-ignore
/phpunit.xml.dist export-ignore
/.gitattributes export-ignore
/.gitignore export-ignore
3 changes: 3 additions & 0 deletions src/Symfony/Component/Notifier/Bridge/Mastodon/.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/Mastodon/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
CHANGELOG
=========

6.3
---

* Add the bridge
19 changes: 19 additions & 0 deletions src/Symfony/Component/Notifier/Bridge/Mastodon/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
Copyright (c) 2022 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.
58 changes: 58 additions & 0 deletions src/Symfony/Component/Notifier/Bridge/Mastodon/MastodonOptions.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
<?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\Mastodon;

use Symfony\Component\Mime\Part\File;
use Symfony\Component\Notifier\Message\MessageOptionsInterface;

final class MastodonOptions implements MessageOptionsInterface
{
public function __construct(
private array $options = [],
) {
}

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

public function getRecipientId(): ?string
{
return null;
}

/**
* @param string[] $choices
*/
public function poll(array $choices, int $expiresIn): self
{
$this->options['poll'] = [
'options' => $choices,
'expires_in' => $expiresIn,
];

return $this;
}

public function attachMedia(File $file, File $thumbnail = null, string $description = null, string $focus = null): self
{
$this->options['attach'][] = [
'file' => $file,
'thumbnail' => $thumbnail,
'description' => $description,
'focus' => $focus,
];

return $this;
}
}
152 changes: 152 additions & 0 deletions src/Symfony/Component/Notifier/Bridge/Mastodon/MastodonTransport.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
<?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\Mastodon;

use Symfony\Component\Mime\Part\DataPart;
use Symfony\Component\Mime\Part\File;
use Symfony\Component\Mime\Part\Multipart\FormDataPart;
use Symfony\Component\Notifier\Exception\RuntimeException;
use Symfony\Component\Notifier\Exception\TransportException;
use Symfony\Component\Notifier\Exception\UnsupportedMessageTypeException;
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\Contracts\EventDispatcher\EventDispatcherInterface;
use Symfony\Contracts\HttpClient\Exception\ExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\HttpClient\ResponseInterface;

/**
* @author Quentin Dequippe <quentin@dequippe.tech>
*
* @see https://docs.joinmastodon.org
*/
final class MastodonTransport extends AbstractTransport
{
public function __construct(#[\SensitiveParameter] private readonly string $accessToken, HttpClientInterface $client = null, EventDispatcherInterface $dispatcher = null)
{
parent::__construct($client, $dispatcher);
}

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

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

public function request(string $method, string $url, array $options): ResponseInterface
{
$url = sprintf('https://%s%s', $this->getEndpoint(), $url);

$options['auth_bearer'] = $this->accessToken;

return $this->client->request($method, $url, $options);
}

/**
* @see https://docs.joinmastodon.org/methods/statuses/
*/
protected function doSend(MessageInterface $message): SentMessage
{
if (!$message instanceof ChatMessage) {
throw new UnsupportedMessageTypeException(__CLASS__, ChatMessage::class, $message);
}

$options = $message->getOptions()?->toArray() ?? [];
$options['status'] = $message->getSubject();
$response = null;

try {
if (isset($options['attach'])) {
$options['media_ids'] = $this->uploadMedia($options['attach']);
unset($options['attach']);
}

$response = $this->request('POST', '/api/v1/statuses', ['json' => $options]);
$statusCode = $response->getStatusCode();
$result = $response->toArray(false);
} catch (ExceptionInterface $e) {
if (null !== $response) {
throw new TransportException($e->getMessage(), $response, 0, $e);
}

throw new RuntimeException($e->getMessage(), 0, $e);
}

if (200 !== $statusCode) {
throw new TransportException(sprintf('Unable to post the Mastodon message: "%s" (%s).', $result['error_description'], $result['error']), $response);
}

$sentMessage = new SentMessage($message, (string) $this);
$sentMessage->setMessageId($result['id']);

return $sentMessage;
}

/**
* @param array<array{file: File, thumbnail: File|null, description: string|null, focus: string}> $media
*/
private function uploadMedia(array $media): array
{
$responses = [];

foreach ($media as [
'file' => $file,
'thumbnail' => $thumbnail,
'description' => $description,
'focus' => $focus,
]) {
$formDataPart = new FormDataPart(array_filter([
'file' => new DataPart($file),
'thumbnail' => $thumbnail ? new DataPart($thumbnail) : null,
'description' => $description,
'focus' => $focus,
]));

$headers = [];
foreach ($formDataPart->getPreparedHeaders()->all() as $header) {
$headers[] = $header->toString();
}

$responses[] = $this->request('POST', '/api/v2/media', [
'headers' => $headers,
'body' => $formDataPart->bodyToIterable(),
]);
}

$mediaIds = [];

try {
foreach ($responses as $i => $response) {
unset($responses[$i]);
$result = $response->toArray(false);

if (300 <= $response->getStatusCode()) {
throw new TransportException(sprintf('Unable to upload media as attachment: "%s" (%s).', $result['error_description'], $result['error']), $response);
}

$mediaIds[] = $result['id'];
}
} finally {
foreach ($responses as $response) {
$response->cancel();
}
}

return $mediaIds;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?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\Mastodon;

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

/**
* @author Quentin Dequippe <quentin@dequippe.tech>
*/
final class MastodonTransportFactory extends AbstractTransportFactory
{
public function create(Dsn $dsn): MastodonTransport
{
$scheme = $dsn->getScheme();

if ('mastodon' !== $scheme) {
throw new UnsupportedSchemeException($dsn, 'mastodon', $this->getSupportedSchemes());
}

$token = $this->getUser($dsn);
$host = $dsn->getHost();
$port = $dsn->getPort();

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

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

Provides Mastodon integration for Symfony Notifier.

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

```
MASTODON_DSN=mastodon://ACCESS_TOKEN@HOST
```

where:
- `ACCESS_TOKEN` is your Mastodon access token
- `HOST` is your Mastodon host

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)
Loading

0 comments on commit aee9ea5

Please sign in to comment.