10000 [Notifier] add Ntfy bridge by mikaelkael · Pull Request #50131 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

[Notifier] add Ntfy bridge #50131

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
Jun 20, 2023
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 @@ -2753,6 +2753,7 @@ private function registerNotifierConfiguration(array $config, ContainerBuilder $
NotifierBridge\MicrosoftTeams\MicrosoftTeamsTransportFactory::class => 'notifier.transport_factory.microsoft-teams',
NotifierBridge\Mobyt\MobytTransportFactory::class => 'notifier.transport_factory.mobyt',
NotifierBridge\Novu\NovuTransportFactory::class => 'notifier.transport_factory.novu',
NotifierBridge\Ntfy\NtfyTransportFactory::class => 'notifier.transport_factory.ntfy',
NotifierBridge\Octopush\OctopushTransportFactory::class => 'notifier.transport_factory.octopush',
NotifierBridge\OneSignal\OneSignalTransportFactory::class => 'notifier.transport_factory.one-signal',
NotifierBridge\OrangeSms\OrangeSmsTransportFactory::class => 'notifier.transport_factory.orange-sms',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -291,5 +291,9 @@
->set('notifier.transport_factory.novu', Bridge\Novu\NovuTransportFactory::class)
->parent('notifier.transport_factory.abstract')
->tag('texter.transport_factory')

->set('notifier.transport_factory.ntfy', Bridge\Ntfy\NtfyTransportFactory::class)
->parent('notifier.transport_factory.abstract')
->tag('texter.transport_factory')
;
};
4 changes: 4 additions & 0 deletions src/Symfony/Component/Notifier/Bridge/Ntfy/.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/Ntfy/.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/Ntfy/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
CHANGELOG
=========

6.4
---

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

use Symfony\Component\Notifier\Exception\LogicException;
use Symfony\Component\Notifier\Message\MessageOptionsInterface;
use Symfony\Component\Notifier\Notification\Notification;

/**
* @author Mickael Perraud <mikaelkael.fr@gmail.com>
*/
final class NtfyOptions implements MessageOptionsInterface
{
public const PRIORITY_URGENT = 5;
public const PRIORITY_HIGH = 4;
public const PRIORITY_DEFAULT = 3;
public const PRIORITY_LOW = 2;
public const PRIORITY_MIN = 1;

public function __construct(private array $options = [])
{
}

public static function fromNotification(Notification $notification): self
{
$options = new self();
$options->setTitle($notification->getSubject());
$options->setMessage($notification->getContent());
$options->setStringPriority($notification->getImportance());
$options->addTag($notification->getEmoji());

return $options;
}

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

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

public function setMessage(string $message): self
{
$this->options['message'] = $message;

return $this;
}

public function setTitle(string $title): self
{
$this->options['title'] = $title;

return $this;
}

public function setStringPriority(string $priority): self
{
switch ($priority) {
case Notification::IMPORTANCE_URGENT:
return $this->setPriority(self::PRIORITY_URGENT);
case Notification::IMPORTANCE_HIGH:
return $this->setPriority(self::PRIORITY_HIGH);
case Notification::IMPORTANCE_LOW:
return $this->setPriority(self::PRIORITY_LOW);
default:
return $this->setPriority(self::PRIORITY_DEFAULT);
}
}

public function setPriority(int $priority): self
{
if (\in_array($priority, [
self::PRIORITY_MIN, self::PRIORITY_LOW, self::PRIORITY_DEFAULT, self::PRIORITY_HIGH, self::PRIORITY_URGENT,
])) {
$this->options['priority'] = $priority;
}

return $this;
}

public function addTag(string $tag): self
{
$this->options['tags'][] = $tag;

return $this;
}

public function setTags(array $tags): self
{
$this->options['tags'] = $tags;

return $this;
}

public function setDelay(\DateTimeInterface $dateTime): self
{
if ($dateTime > (new \DateTime())) {
$this->options['delay'] = (string) $dateTime->getTimestamp();
} else {
throw new LogicException('Delayed date must be defined in the future.');
}

return $this;
}

public function setActions(array $actions): self
{
$this->options['actions'] = $actions;

return $this;
}

public function addAction(array $action): self
{
$this->options['actions'][] = $action;

return $this;
}

public function setClick(string $url): self
{
$this->options['click'] = $url;

return $this;
}

public function setAttachment(string $attachment): self
{
$this->options['attach'] = $attachment;

return $this;
}

public function setFilename(string $filename): self
{
$this->options['filename'] = $filename;

return $this;
}

public function setEmail(string $email): self
{
$this->options['email'] = $email;

return $this;
}

public function setCache(bool $enable): self
{
if (!$enable) {
$this->options['cache'] = 'no';
} else {
unset($this->options['cache']);
}

return $this;
}

public function setFirebase(bool $enable): self
{
if (!$enable) {
$this->options['firebase'] = 'no';
} else {
unset($this->options['firebase']);
}

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

use Symfony\Component\Notifier\Exception\LogicException;
use Symfony\Component\Notifier\Exception\TransportException;
use Symfony\Component\Notifier\Exception\UnsupportedMessageTypeException;
use Symfony\Component\Notifier\Message\MessageInterface;
use Symfony\Component\Notifier\Message\PushMessage;
use Symfony\Component\Notifier\Message\SentMessage;
use Symfony\Component\Notifier\Transport\AbstractTransport;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;

/**
* @author Mickael Perraud <mikaelkael.fr@gmail.com>
*/
final class NtfyTransport extends AbstractTransport
{
protected const HOST = 'ntfy.sh';
private ?string $user = null;
private ?string $password = null;

public function __construct(private string $topic, private bool $secureHttp = true, HttpClientInterface $client = null, EventDispatcherInterface $dispatcher = null)
{
parent::__construct($client, $dispatcher);
}

public function getTopic(): string
{
return $this->topic;
}

public function setPassword(?string $password): self
{
$this->password = $password;

return $this;
}

public function setUser(?string $user): self
{
$this->user = $user;

return $this;
}

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

if ($message->getOptions() && !$message->getOptions() instanceof NtfyOptions) {
throw new LogicException(sprintf('The "%s" transport only supports instances of "%s" for options.', __CLASS__, NtfyOptions::class));
}

if (!($opts = $message->getOptions()) && $notification = $message->getNotification()) {
$opts = NtfyOptions::fromNotification($notification);
}

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

$options['topic'] = $this->getTopic();

if (!isset($options['title'])) {
$options['title'] = $message->getSubject();
}
if (!isset($options['message'])) {
$options['message'] = $message->getContent();
}

$headers = [];

if (null !== $this->user && null !== $this->password) {
$headers['Authorization'] = 'Basic '.rtrim(base64_encode($this->user.':'.$this->password), '=');
}

$response = $this->client->request('POST', ($this->secureHttp ? 'https' : 'http').'://'.$this->getEndpoint(), [
'headers' => $headers,
'json' => $options,
]);

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

if (200 !== $statusCode) {
throw new TransportException(sprintf('Unable to send the Ntfy push notification: "%s".', $response->getContent(false)), $response);
}

$result = $response->toArray(false);

if (empty($result['id'])) {
throw new TransportException(sprintf('Unable to send the Ntfy push notification: "%s".', $response->getContent(false)), $response);
}

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

return $sentMessage;
}

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

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