Skip to content

[Notifier] Add Google Chat bridge #36488

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
Aug 7, 2020
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 @@ -96,6 +96,7 @@
use Symfony\Component\Mime\MimeTypes;
use Symfony\Component\Notifier\Bridge\Firebase\FirebaseTransportFactory;
use Symfony\Component\Notifier\Bridge\FreeMobile\FreeMobileTransportFactory;
use Symfony\Component\Notifier\Bridge\GoogleChat\GoogleChatTransportFactory;
use Symfony\Component\Notifier\Bridge\Mattermost\MattermostTransportFactory;
use Symfony\Component\Notifier\Bridge\Nexmo\NexmoTransportFactory;
use Symfony\Component\Notifier\Bridge\OvhCloud\OvhCloudTransportFactory;
Expand Down Expand Up @@ -2076,6 +2077,7 @@ private function registerNotifierConfiguration(array $config, ContainerBuilder $
SlackTransportFactory::class => 'notifier.transport_factory.slack',
TelegramTransportFactory::class => 'notifier.transport_factory.telegram',
MattermostTransportFactory::class => 'notifier.transport_factory.mattermost',
GoogleChatTransportFactory::class => 'notifier.transport_factory.googlechat',
NexmoTransportFactory::class => 'notifier.transport_factory.nexmo',
RocketChatTransportFactory::class => 'notifier.transport_factory.rocketchat',
TwilioTransportFactory::class => 'notifier.transport_factory.twilio',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

use Symfony\Component\Notifier\Bridge\Firebase\FirebaseTransportFactory;
use Symfony\Component\Notifier\Bridge\FreeMobile\FreeMobileTransportFactory;
use Symfony\Component\Notifier\Bridge\GoogleChat\GoogleChatTransportFactory;
use Symfony\Component\Notifier\Bridge\Mattermost\MattermostTransportFactory;
use Symfony\Component\Notifier\Bridge\Nexmo\NexmoTransportFactory;
use Symfony\Component\Notifier\Bridge\OvhCloud\OvhCloudTransportFactory;
Expand Down Expand Up @@ -51,6 +52,10 @@
->parent('notifier.transport_factory.abstract')
->tag('chatter.transport_factory')

->set('notifier.transport_factory.googlechat', GoogleChatTransportFactory::class)
->parent('notifier.transport_factory.abstract')
->tag('chatter.transport_factory')

->set('notifier.transport_factory.twilio', TwilioTransportFactory::class)
->parent('notifier.transport_factory.abstract')
->tag('texter.transport_factory')
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
/Tests export-ignore
/phpunit.xml.dist export-ignore
/.gitignore export-ignore
7 changes: 7 additions & 0 deletions src/Symfony/Component/Notifier/Bridge/GoogleChat/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
CHANGELOG
=========

5.2.0
-----

* Added the bridge
Original file line number Diff line number Diff line change
@@ -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\GoogleChat;

use Symfony\Component\Notifier\Bridge\GoogleChat\Component\Card;
use Symfony\Component\Notifier\Message\ChatMessage;
use Symfony\Component\Notifier\Message\MessageOptionsInterface;
use Symfony\Component\Notifier\Notification\Notification;

/**
* @author Jérôme Tamarelle <jerome@tamarelle.net>
*
* @experimental in 5.2
*/
final class GoogleChatOptions implements MessageOptionsInterface
{
private $threadKey;
private $options = [];

public function __construct(array $options = [])
{
$this->options = $options;
}

public static function fromNotification(Notification $notification): self
{
$options = new self();

$text = $notification->getEmoji().' *'.$notification->getSubject().'* ';

if ($notification->getContent()) {
$text .= "\r\n".$notification->getContent();
}
if ($exception = $notification->getExceptionAsString()) {
$text .= "\r\n".'```'.$notification->getExceptionAsString().'```';
}

$options->text($text);

return $options;
}

public static function fromMessage(ChatMessage $message): self
{
$options = new self();

$options->text($message->getSubject());

return $options;
}

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

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

return $this;
}

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

return $this;
}

public function setThreadKey(?string $threadKey): self
{
$this->threadKey = $threadKey;

return $this;
}

public function getThreadKey(): ?string
{
return $this->threadKey;
}

public function getRecipientId(): ?string
{
return null;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
<?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\GoogleChat;

use Symfony\Component\HttpClient\Exception\JsonException;
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\Message\SentMessage;
use Symfony\Component\Notifier\Transport\AbstractTransport;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;

/**
* @author Jérôme Tamarelle <jerome@tamarelle.net>
*
* @internal
*
* @experimental in 5.2
*/
final class GoogleChatTransport extends AbstractTransport
{
protected const HOST = 'chat.googleapis.com';

private $space;
private $accessKey;
private $accessToken;

/**
* @var ?string
*/
private $threadKey;

/**
* @param string $space The space name the the webhook url "/v1/spaces/<space>/messages"
* @param string $accessKey The "key" parameter of the webhook url
* @param string $accessToken The "token" parameter of the webhook url
*/
public function __construct(string $space, string $accessKey, string $accessToken, HttpClientInterface $client = null, EventDispatcherInterface $dispatcher = null)
{
$this->space = $space;
$this->accessKey = $accessKey;
$this->accessToken = $accessToken;

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

/**
* Opaque thread identifier string that can be specified to group messages into a single thread.
* If this is the first message with a given thread identifier, a new thread is created.
* Subsequent messages with the same thread identifier will be posted into the same thread.
*
* @see https://developers.google.com/hangouts/chat/reference/rest/v1/spaces.messages/create#query-parameters
*/
public function setThreadKey(?string $threadKey): self
{
$this->threadKey = $threadKey;

return $this;
}

public function __toString(): string
{
return sprintf('googlechat://%s/%s%s',
$this->getEndpoint(),
$this->space,
$this->threadKey ? '?threadKey='.urlencode($this->threadKey) : ''
);
}

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

/**
* @see https://developers.google.com/hangouts/chat/how-tos/webhooks
*/
protected function doSend(MessageInterface $message): SentMessage
{
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)));
}
if ($message->getOptions() && !$message->getOptions() instanceof GoogleChatOptions) {
throw new LogicException(sprintf('The "%s" transport only supports instances of "%s" for options.', __CLASS__, GoogleChatOptions::class));
}

$opts = $message->getOptions();
if (!$opts) {
if ($notification = $message->getNotification()) {
$opts = GoogleChatOptions::fromNotification($notification);
} else {
$opts = GoogleChatOptions::fromMessage($message);
}
}

if (null !== $this->threadKey && null === $opts->getThreadKey()) {
$opts->setThreadKey($this->threadKey);
}

$threadKey = $opts->getThreadKey() ?: $this->threadKey;

$options = $opts->toArray();
$url = sprintf('https://%s/v1/spaces/%s/messages?key=%s&token=%s%s',
$this->getEndpoint(),
$this->space,
urlencode($this->accessKey),
urlencode($this->accessToken),
$threadKey ? '&threadKey='.urlencode($threadKey) : ''
);
$response = $this->client->request('POST', $url, [
'json' => array_filter($options),
]);

try {
$result = $response->toArray(false);
} catch (JsonException $jsonException) {
throw new TransportException(sprintf('Unable to post the Google Chat message: Invalid response.'), $response, $response->getStatusCode(), $jsonException);
}

if (200 !== $response->getStatusCode()) {
throw new TransportException(sprintf('Unable to post the Google Chat message: "%s".', $result['error']['message'] ?? $response->getContent(false)), $response, $result['error']['code'] ?? $response->getStatusCode());
}

if (!\array_key_exists('name', $result)) {
throw new TransportException(sprintf('Unable to post the Google Chat message: "%s".', $response->getContent(false)), $response);
}

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

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

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 Jérôme Tamarelle <jerome@tamarelle.net>
*
* @experimental in 5.2
*/
final class GoogleChatTransportFactory extends AbstractTransportFactory
{
/**
* @param Dsn $dsn Format: googlechat://<key>:<token>@default/<space>?threadKey=<thread>
*
* @return GoogleChatTransport
*/
public function create(Dsn $dsn): TransportInterface
{
$scheme = $dsn->getScheme();

if ('googlechat' === $scheme) {
$space = explode('/', $dsn->getPath())[1];
$accessKey = $this->getUser($dsn);
$accessToken = $this->getPassword($dsn);
$threadKey = $dsn->getOption('threadKey');
$host = 'default' === $dsn->getHost() ? null : $dsn->getHost();
$port = $dsn->getPort();

return (new GoogleChatTransport($space, $accessKey, $accessToken, $this->client, $this->dispatcher))
->setThreadKey($threadKey)
->setHost($host)
->setPort($port);
}

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

protected function getSupportedSchemes(): array
{
return ['googlechat'];
}
}
19 changes: 19 additions & 0 deletions src/Symfony/Component/Notifier/Bridge/GoogleChat/LICENSE
Original file line number Diff line number Diff line change
@@ -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.
14 changes: 14 additions & 0 deletions src/Symfony/Component/Notifier/Bridge/GoogleChat/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
Google Chat Notifier
====================

Provides Google Chat integration for Symfony Notifier.

googlechat://ACCESS_KEY:ACCESS_TOKEN@default/SPACE?threadKey=THREAD_KEY

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