Skip to content

[Notifier] Add notifier for Microsoft Teams #39007

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
Apr 8, 2021
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 @@ -125,6 +125,7 @@
use Symfony\Component\Notifier\Bridge\LinkedIn\LinkedInTransportFactory;
use Symfony\Component\Notifier\Bridge\Mattermost\MattermostTransportFactory;
use Symfony\Component\Notifier\Bridge\Mercure\MercureTransportFactory;
use Symfony\Component\Notifier\Bridge\MicrosoftTeams\MicrosoftTeamsTransportFactory;
use Symfony\Component\Notifier\Bridge\Mobyt\MobytTransportFactory;
use Symfony\Component\Notifier\Bridge\Nexmo\NexmoTransportFactory;
use Symfony\Component\Notifier\Bridge\Octopush\OctopushTransportFactory;
Expand Down Expand Up @@ -2390,6 +2391,7 @@ private function registerNotifierConfiguration(array $config, ContainerBuilder $
MercureTransportFactory::class => 'notifier.transport_factory.mercure',
GitterTransportFactory::class => 'notifier.transport_factory.gitter',
ClickatellTransportFactory::class => 'notifier.transport_factory.clickatell',
MicrosoftTeamsTransportFactory::class => 'notifier.transport_factory.microsoftteams',
];

$parentPackages = ['symfony/framework-bundle', 'symfony/notifier'];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
use Symfony\Component\Notifier\Bridge\LinkedIn\LinkedInTransportFactory;
use Symfony\Component\Notifier\Bridge\Mattermost\MattermostTransportFactory;
use Symfony\Component\Notifier\Bridge\Mercure\MercureTransportFactory;
use Symfony\Component\Notifier\Bridge\MicrosoftTeams\MicrosoftTeamsTransportFactory;
use Symfony\Component\Notifier\Bridge\Mobyt\MobytTransportFactory;
use Symfony\Component\Notifier\Bridge\Nexmo\NexmoTransportFactory;
use Symfony\Component\Notifier\Bridge\Octopush\OctopushTransportFactory;
Expand Down Expand Up @@ -150,6 +151,10 @@
->parent('notifier.transport_factory.abstract')
->tag('chatter.transport_factory')

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

->set('notifier.transport_factory.gatewayapi', GatewayApiTransportFactory::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,4 @@
/Tests export-ignore
/phpunit.xml.dist export-ignore
/.gitattributes export-ignore
/.gitignore export-ignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
vendor/
composer.lock
phpunit.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
CHANGELOG
=========

5.3
---

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

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\HttpClientInterface;

/**
* @author Edouard Lescot <edouard.lescot@gmail.com>
* @author Oskar Stark <oskarstark@googlemail.com>
*/
final class MicrosoftTeamsTransport extends AbstractTransport
{
protected const ENDPOINT = 'outlook.office.com';

private $path;

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

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

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

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

/**
* @see https://docs.microsoft.com/en-us/microsoftteams/platform/webhooks-and-connectors/how-to/connectors-using#post-a-message-to-the-webhook-using-curl
*/
protected function doSend(MessageInterface $message): SentMessage
{
if (!$message instanceof ChatMessage) {
throw new UnsupportedMessageTypeException(__CLASS__, ChatMessage::class, $message);
}

$path = $message->getRecipientId() ?? $this->path;
$endpoint = sprintf('https://%s%s', $this->getEndpoint(), $path);
$response = $this->client->request('POST', $endpoint, [
'json' => [
'title' => $message->getSubject(),
],
]);

$requestId = $response->getHeaders(false)['request-id'][0] ?? null;
if (null === $requestId) {
$originalContent = $message->getSubject();

throw new TransportException(sprintf('Unable to post the Microsoft Teams message: "%s" (request-id not found).', $originalContent), $response);
}

if (200 !== $response->getStatusCode()) {
$errorMessage = $response->getContent(false);
$originalContent = $message->getSubject();

throw new TransportException(sprintf('Unable to post the Microsoft Teams message: "%s" (%s : "%s").', $originalContent, $requestId, $errorMessage), $response);
}

$message = new SentMessage($message, (string) $this);
$message->setMessageId($requestId);

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

use Symfony\Component\Notifier\Exception\IncompleteDsnException;
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 Edouard Lescot <edouard.lescot@gmail.com>
* @author Oskar Stark <oskarstark@googlemail.com>
*/
final class MicrosoftTeamsTransportFactory extends AbstractTransportFactory
{
public function create(Dsn $dsn): TransportInterface
{
$scheme = $dsn->getScheme();

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

$path = $dsn->getPath();

if (null === $path) {
throw new IncompleteDsnException('Path is not set.', $dsn->getOriginalDsn());
}

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

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

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

Provides [Microsoft Teams](https://www.microsoft.com/en/microsoft-365/microsoft-teams/free) integration
through Incoming Webhook for Symfony Notifier.

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

```
MICROSOFT_TEAMS_DSN=microsoftteams://default/PATH
```

where:
- `PATH` has the following format: `webhook/{uuid}@{uuid}/IncomingWebhook/{id}/{uuid}`

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)
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?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\MicrosoftTeams\Tests;

use Symfony\Component\Notifier\Bridge\MicrosoftTeams\MicrosoftTeamsTransportFactory;
use Symfony\Component\Notifier\Test\TransportFactoryTestCase;
use Symfony\Component\Notifier\Transport\TransportFactoryInterface;

final class MicrosoftTeamsTransportFactoryTest extends TransportFactoryTestCase
{
public function createFactory(): TransportFactoryInterface
{
return new MicrosoftTeamsTransportFactory();
}

public function createProvider(): iterable
{
yield [
'microsoftteams://host/webhook',
'microsoftteams://host/webhook',
];
}

public function supportsProvider(): iterable
{
yield [true, 'microsoftteams://host/webhook'];
yield [false, 'somethingElse://host/webhook'];
}

public function unsupportedSchemeProvider(): iterable
{
yield ['somethingElse://host/webhook'];
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
<?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\MicrosoftTeams\Tests;

use Symfony\Component\HttpClient\MockHttpClient;
use Symfony\Component\HttpClient\Response\MockResponse;
use Symfony\Component\Notifier\Bridge\MicrosoftTeams\MicrosoftTeamsTransport;
use Symfony\Component\Notifier\Exception\TransportException;
use Symfony\Component\Notifier\Message\ChatMessage;
use Symfony\Component\Notifier\Message\MessageInterface;
use Symfony\Component\Notifier\Message\SmsMessage;
use Symfony\Component\Notifier\Test\TransportTestCase;
use Symfony\Component\Notifier\Transport\TransportInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\HttpClient\ResponseInterface;

final class MicrosoftTeamsTransportTest extends TransportTestCase
{
/**
* @return MicrosoftTeamsTransport
*/
public function createTransport(?HttpClientInterface $client = null): TransportInterface
{
return (new MicrosoftTeamsTransport('/testPath', $client ?: $this->createMock(HttpClientInterface::class)))->setHost('host.test');
}

public function toStringProvider(): iterable
{
yield ['microsoftteams://host.test/testPath', $this->createTransport()];
}

public function supportedMessagesProvider(): iterable
{
yield [new ChatMessage('Hello!')];
}

public function unsupportedMessagesProvider(): iterable
{
yield [new SmsMessage('0611223344', 'Hello!')];
yield [$this->createMock(MessageInterface::class)];
}

public function testSendWithErrorResponseThrows()
{
$client = new MockHttpClient(function (string $method, string $url, array $options = []): ResponseInterface {
return new MockResponse('testErrorMessage', ['response_headers' => ['request-id' => ['testRequestId']], 'http_code' => 400]);
});

$transport = $this->createTransport($client);

$this->expectException(TransportException::class);
$this->expectExceptionMessageMatches('/testErrorMessage/');

$transport->send(new ChatMessage('testMessage'));
}

public function testSendWithErrorRequestIdThrows()
{
$client = new MockHttpClient(new MockResponse());

$transport = $this->createTransport($client);

$this->expectException(TransportException::class);
$this->expectExceptionMessageMatches('/request-id not found/');

$transport->send(new ChatMessage('testMessage'));
}

public function testSend()
{
$message = 'testMessage';

$expectedBody = json_encode(['title' => $message]);

$client = new MockHttpClient(function (string $method, string $url, array $options = []) use ($expectedBody): ResponseInterface {
$this->assertJsonStringEqualsJsonString($expectedBody, $options['body']);

return new MockResponse('1', ['response_headers' => ['request-id' => ['testRequestId']], 'http_code' => 200]);
});

$transport = $this->createTransport($client);

$transport->send(new ChatMessage($message));
}
}
Loading