Skip to content

Commit

Permalink
feature #33968 [Notifier] Add Firebase bridge (Jeroeny)
Browse files Browse the repository at this point in the history
This PR was squashed before being merged into the 5.1-dev branch (closes #33968).

Discussion
----------

[Notifier] Add Firebase bridge

| Q             | A
| ------------- | ---
| Branch?       | master
| Bug fix?      | no
| New feature?  | yes
| Deprecations? | no
| Tickets       | See #33687
| License       | MIT

This would add [Firebase](https://firebase.google.com) integration for the Notifier component. With Firebase you can send push notifications to the users of you Android and iOS app and website (formerly known as Google Cloud messaging).

I'm not sure if it's possible to have this merged, like the other bridges. Or if I should create a stand-alone repository? That'd be fine too.

Also it's now using the `ChatMessage` as implementation of `Symfony\Component\Notifier\Message\MessageInterface`, but I feel like this component could use a `PushMessage` or something similar. Although I'm not sure if it would contain more than `subject` that the `ChatMessage` does.

Commits
-------

2776d2f [Notifier] Add Firebase bridge
  • Loading branch information
fabpot committed Feb 10, 2020
2 parents 1d472a6 + 2776d2f commit 7e4abf5
Show file tree
Hide file tree
Showing 16 changed files with 529 additions and 0 deletions.
Expand Up @@ -90,6 +90,7 @@
use Symfony\Component\Messenger\Transport\TransportInterface;
use Symfony\Component\Mime\MimeTypeGuesserInterface;
use Symfony\Component\Mime\MimeTypes;
use Symfony\Component\Notifier\Bridge\Firebase\FirebaseTransportFactory;
use Symfony\Component\Notifier\Bridge\Mattermost\MattermostTransportFactory;
use Symfony\Component\Notifier\Bridge\Nexmo\NexmoTransportFactory;
use Symfony\Component\Notifier\Bridge\RocketChat\RocketChatTransportFactory;
Expand Down Expand Up @@ -2003,6 +2004,7 @@ private function registerNotifierConfiguration(array $config, ContainerBuilder $
NexmoTransportFactory::class => 'notifier.transport_factory.nexmo',
RocketChatTransportFactory::class => 'notifier.transport_factory.rocketchat',
TwilioTransportFactory::class => 'notifier.transport_factory.twilio',
FirebaseTransportFactory::class => 'notifier.transport_factory.firebase',
];

foreach ($classToServices as $class => $service) {
Expand Down
Expand Up @@ -34,6 +34,10 @@
<tag name="texter.transport_factory" />
</service>

<service id="notifier.transport_factory.firebase" class="Symfony\Component\Notifier\Bridge\Firebase\FirebaseTransportFactory" parent="notifier.transport_factory.abstract">
<tag name="texter.transport_factory" />
</service>

<service id="notifier.transport_factory.null" class="Symfony\Component\Notifier\Transport\NullTransportFactory" parent="notifier.transport_factory.abstract">
<tag name="notifier.transport_factory" />
</service>
Expand Down
2 changes: 2 additions & 0 deletions src/Symfony/Component/Notifier/Bridge/Firebase/.gitattributes
@@ -0,0 +1,2 @@
/Tests export-ignore
/phpunit.xml.dist export-ignore
7 changes: 7 additions & 0 deletions src/Symfony/Component/Notifier/Bridge/Firebase/CHANGELOG.md
@@ -0,0 +1,7 @@
CHANGELOG
=========

5.1.0
-----

* Created the bridge
67 changes: 67 additions & 0 deletions src/Symfony/Component/Notifier/Bridge/Firebase/FirebaseOptions.php
@@ -0,0 +1,67 @@
<?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\Firebase;

use Symfony\Component\Notifier\Message\MessageOptionsInterface;

/**
* @author Jeroen Spee <https://github.com/Jeroeny>
*
* @see https://firebase.google.com/docs/cloud-messaging/xmpp-server-ref.html
*
* @experimental in 5.1
*/
abstract class FirebaseOptions implements MessageOptionsInterface
{
/** @var string the recipient */
private $to;

/**
* @var array
*
* @see https://firebase.google.com/docs/cloud-messaging/xmpp-server-ref.html#notification-payload-support
*/
protected $options;

public function __construct(string $to, array $options)
{
$this->to = $to;
$this->options = $options;
}

public function toArray(): array
{
return [
'to' => $this->to,
'notification' => $this->options,
];
}

public function getRecipientId(): ?string
{
return $this->to;
}

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

return $this;
}

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

return $this;
}
}
@@ -0,0 +1,88 @@
<?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\Firebase;

use Symfony\Component\Notifier\Exception\InvalidArgumentException;
use Symfony\Component\Notifier\Exception\LogicException;
use Symfony\Component\Notifier\Exception\TransportException;
use Symfony\Component\Notifier\Message\ChatMessage;
use Symfony\Component\Notifier\Message\MessageInterface;
use Symfony\Component\Notifier\Transport\AbstractTransport;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;

/**
* @author Jeroen Spee <https://github.com/Jeroeny>
*
* @experimental in 5.1
*/
final class FirebaseTransport extends AbstractTransport
{
protected const HOST = 'fcm.googleapis.com/fcm/send';

/** @var string */
private $token;

public function __construct(string $token, HttpClientInterface $client = null, EventDispatcherInterface $dispatcher = null)
{
$this->token = $token;
$this->client = $client;

parent::__construct($client, $dispatcher);
}

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

public function supports(MessageInterface $message): bool
{
return $message instanceof ChatMessage;
}

protected function doSend(MessageInterface $message): void
{
if (!$message instanceof ChatMessage) {
throw new LogicException(sprintf('The "%s" transport only supports instances of "%s" (instance of "%s" given).', __CLASS__, ChatMessage::class, \get_class($message)));
}

$endpoint = sprintf('https://%s', $this->getEndpoint());
$options = ($opts = $message->getOptions()) ? $opts->toArray() : [];
if (!isset($options['to'])) {
$options['to'] = $message->getRecipientId();
}
if (null === $options['to']) {
throw new InvalidArgumentException(sprintf('The "%s" transport required the "to" option to be set', __CLASS__));
}
$options['notification'] = $options['notification'] ?? [];
$options['notification']['body'] = $message->getSubject();
$response = $this->client->request('POST', $endpoint, [
'headers' => [
'Authorization' => sprintf('key=%s', $this->token),
],
'json' => array_filter($options),
]);

$contentType = $response->getHeaders(false)['Content-Type'] ?? '';
$jsonContents = 0 === strpos($contentType, 'application/json') ? $response->toArray(false) : null;

if (200 !== $response->getStatusCode()) {
$errorMessage = $jsonContents ? $jsonContents['results']['error'] : $response->getContent(false);

throw new TransportException(sprintf('Unable to post the Firebase message: %s.', $errorMessage), $response);
}
if ($jsonContents && isset($jsonContents['results']['error'])) {
throw new TransportException(sprintf('Unable to post the Firebase message: %s.', $jsonContents['error']), $response);
}
}
}
@@ -0,0 +1,44 @@
<?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\Firebase;

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

/**
* @author Jeroen Spee <https://github.com/Jeroeny>
*
* @experimental in 5.1
*/
final class FirebaseTransportFactory extends AbstractTransportFactory
{
public function create(Dsn $dsn): TransportInterface
{
$scheme = $dsn->getScheme();
$token = sprintf('%s:%s', $this->getUser($dsn), $this->getPassword($dsn));
$host = 'default' === $dsn->getHost() ? null : $dsn->getHost();
$port = $dsn->getPort();

if ('firebase' === $scheme) {
return (new FirebaseTransport($token, $this->client, $this->dispatcher))->setHost($host)->setPort($port);
}

throw new UnsupportedSchemeException($dsn, 'firebase', $this->getSupportedSchemes());
}

protected function getSupportedSchemes(): array
{
return ['firebase'];
}
}
19 changes: 19 additions & 0 deletions src/Symfony/Component/Notifier/Bridge/Firebase/LICENSE
@@ -0,0 +1,19 @@
Copyright (c) 2019 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.
@@ -0,0 +1,96 @@
<?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\Firebase\Notification;

use Symfony\Component\Notifier\Bridge\Firebase\FirebaseOptions;

/**
* @experimental in 5.1
*/
final class AndroidNotification extends FirebaseOptions
{
public function channelId(string $channelId): self
{
$this->options['android_channel_id'] = $channelId;

return $this;
}

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

return $this;
}

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

return $this;
}

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

return $this;
}

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

return $this;
}

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

return $this;
}

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

return $this;
}

/**
* @param string[] $bodyLocArgs
*/
public function bodyLocArgs(array $bodyLocArgs): self
{
$this->options['body_loc_args'] = $bodyLocArgs;

return $this;
}

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

return $this;
}

/**
* @param string[] $titleLocArgs
*/
public function titleLocArgs(array $titleLocArgs): self
{
$this->options['title_loc_args'] = $titleLocArgs;

return $this;
}
}

0 comments on commit 7e4abf5

Please sign in to comment.