Skip to content

[Notifier] Add LINE Bot bridge #58527

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
Oct 14, 2024
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 @@ -2839,6 +2839,7 @@ private function registerNotifierConfiguration(array $config, ContainerBuilder $
NotifierBridge\JoliNotif\JoliNotifTransportFactory::class => 'notifier.transport_factory.joli-notif',
NotifierBridge\KazInfoTeh\KazInfoTehTransportFactory::class => 'notifier.transport_factory.kaz-info-teh',
NotifierBridge\LightSms\LightSmsTransportFactory::class => 'notifier.transport_factory.light-sms',
NotifierBridge\LineBot\LineBotTransportFactory::class => 'notifier.transport_factory.line-bot',
NotifierBridge\LineNotify\LineNotifyTransportFactory::class => 'notifier.transport_factory.line-notify',
NotifierBridge\LinkedIn\LinkedInTransportFactory::class => 'notifier.transport_factory.linked-in',
NotifierBridge\Lox24\Lox24TransportFactory::class => 'notifier.transport_factory.lox24',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
'fake-chat' => Bridge\FakeChat\FakeChatTransportFactory::class,
'firebase' => Bridge\Firebase\FirebaseTransportFactory::class,
'google-chat' => Bridge\GoogleChat\GoogleChatTransportFactory::class,
'line-bot' => Bridge\LineBot\LineBotTransportFactory::class,
'line-notify' => Bridge\LineNotify\LineNotifyTransportFactory::class,
'linked-in' => Bridge\LinkedIn\LinkedInTransportFactory::class,
'mastodon' => Bridge\Mastodon\MastodonTransportFactory::class,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
/Tests export-ignore
/phpunit.xml.dist export-ignore
/.git* export-ignore

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions src/Symfony/Component/Notifier/Bridge/LineBot/.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/LineBot/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
CHANGELOG
=========

7.2
---

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

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 Yi-Jyun Pan <me@pan93.com>
*/
final class LineBotTransport extends AbstractTransport
{
protected const HOST = 'api.line.me';

public function __construct(
#[\SensitiveParameter] private readonly string $accessToken,
private readonly string $receiver,
?HttpClientInterface $client = null,
?EventDispatcherInterface $dispatcher = null,
) {
parent::__construct($client, $dispatcher);
}

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

$response = $this->client->request(
'POST',
\sprintf('https://%s/v2/bot/message/push', $this->getEndpoint()),
[
'auth_bearer' => $this->accessToken,
'json' => [
'to' => $this->receiver,
'messages' => [
[
'type' => 'text',
'text' => $message->getSubject(),
],
],
],
],
);

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

if (200 !== $statusCode) {
$originalContent = $message->getSubject();

$result = $response->toArray(false) ?: ['message' => ''];
if (!isset($result['message']) || !\is_string($result['message'])) {
$result['message'] = '';
}

throw new TransportException(\sprintf('Unable to post the LINE message: "%s" (%d: "%s").', $originalContent, $statusCode, trim($result['message'])), $response);
}

return new SentMessage($message, (string) $this);
}

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

public function __toString(): string
{
return \sprintf('linebot://%s?receiver=%s', $this->getEndpoint(), $this->receiver);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?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\LineBot;

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

/**
* @author Yi-Jyun Pan <me@pan93.com>
*/
final class LineBotTransportFactory extends AbstractTransportFactory
{
private const SCHEME = 'linebot';

protected function getSupportedSchemes(): array
{
return [self::SCHEME];
}

public function create(Dsn $dsn): LineBotTransport
{
if (self::SCHEME !== $dsn->getScheme()) {
throw new UnsupportedSchemeException($dsn, self::SCHEME, $this->getSupportedSchemes());
}

$accessToken = $this->getUser($dsn);
$receiver = $dsn->getRequiredOption('receiver');
if (!\is_string($receiver)) {
throw new InvalidArgumentException('The "receiver" option must be a string.');
}

$host = 'default' === $dsn->getHost() ? null : $dsn->getHost();
$port = $dsn->getPort();

return (new LineBotTransport($accessToken, $receiver, $this->client, $this->dispatcher))->setHost($host)->setPort($port);
}
}
24 changes: 24 additions & 0 deletions src/Symfony/Component/Notifier/Bridge/LineBot/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
LINE Bot Bridge
===============

Provides [LINE Bot (Push Message)](https://developers.line.biz/en/reference/messaging-api/#send-push-message) integration for Symfony Notifier.

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

```
linebot://TOKEN@default?receiver=RECEIVER
```

where:

- `TOKEN` should be encoded in URL format.
- `RECEIVER` can be retrieved from https://developers.line.biz/en/docs/messaging-api/getting-user-ids/#getting-user-ids.

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,77 @@
<?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\LineBot\Tests;

use Symfony\Component\Notifier\Bridge\LineBot\LineBotTransportFactory;
use Symfony\Component\Notifier\Test\AbstractTransportFactoryTestCase;
use Symfony\Component\Notifier\Test\IncompleteDsnTestTrait;
use Symfony\Component\Notifier\Test\MissingRequiredOptionTestTrait;
use Symfony\Component\Notifier\Transport\Dsn;

/**
* @author Yi-Jyun Pan <me@pan93.com>
*/
final class LineBotTransportFactoryTest extends AbstractTransportFactoryTestCase
{
use IncompleteDsnTestTrait;
use MissingRequiredOptionTestTrait;

private const MOCK_TOKEN = 'eyJhbGciOiJIUzI1NiJ9.eyJSb2xlIjoiQWRtaW4iL+CJJc3N1ZXIiOiJJc3N1ZXIiLCJVc2VybmFtZSI6IkphdmFJblVzZSIsImV4cCI6MTcyODU1MjA3OSwiaW+F0IjoxNzI4NTUyMDc5fQ.SPKpGKwsXBay2uXDh7tATW20S2vZpw9qcmYjNp46Ir/AB/12345677=';

public function createFactory(): LineBotTransportFactory
{
return new LineBotTransportFactory();
}

public static function supportsProvider(): iterable
{
yield [true, 'linebot://host?receiver=abc&token=token'];
yield [true, 'linebot://host'];
yield [false, 'somethingElse://host'];
}

public static function createProvider(): iterable
{
$encodedToken = urlencode(self::MOCK_TOKEN);

yield [
'linebot://api.line.me?receiver=test',
'linebot://'.$encodedToken.'@default?receiver=test',
];
}

public static function incompleteDsnProvider(): iterable
{
yield ['linebot://host.test?receiver=xxx', 'User is not set.'];
}

public static function missingRequiredOptionProvider(): iterable
{
yield ['linebot://token@host', 'receiver'];
}

public static function unsupportedSchemeProvider(): iterable
{
yield ['somethingElse://token@host'];
yield ['somethingElse://token@host?receiver=abc&token=token'];
}

public function testDsnToken()
{
$encodedToken = urlencode(self::MOCK_TOKEN);

$uri = "linebot://$encodedToken@default?receiver=test";
$dsn = new Dsn($uri);

$this->assertSame(self::MOCK_TOKEN, $dsn->getUser());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
<?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\LineBot\Tests;

use Symfony\Component\HttpClient\MockHttpClient;
use Symfony\Component\Notifier\Bridge\LineBot\LineBotTransport;
use Symfony\Component\Notifier\Exception\TransportException;
use Symfony\Component\Notifier\Message\ChatMessage;
use Symfony\Component\Notifier\Message\SmsMessage;
use Symfony\Component\Notifier\Test\TransportTestCase;
use Symfony\Component\Notifier\Tests\Transport\DummyMessage;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\HttpClient\ResponseInterface;

/**
* @author Yi-Jyun Pan <me@pan93.com>
*/
final class LineBotTransportTest extends TransportTestCase
{
public static function createTransport(?HttpClientInterface $client = null): LineBotTransport
{
return (new LineBotTransport('testToken', 'testReceiver', $client ?? new MockHttpClient()))->setHost('host.test');
}

public static function toStringProvider(): iterable
{
yield ['linebot://host.test?receiver=testReceiver', self::createTransport()];
}

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

public static function unsupportedMessagesProvider(): iterable
{
yield [new SmsMessage('0611223344', 'Hello!')];
yield [new DummyMessage()];
}

public function testSendWithErrorResponseThrows()
{
$response = $this->createMock(ResponseInterface::class);
$response->expects($this->exactly(2))
->method('getStatusCode')
->willReturn(400);
$response->expects($this->once())
->method('getContent')
->willReturn(json_encode(['message' => 'testDescription']));

$client = new MockHttpClient(static fn (): ResponseInterface => $response);

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

$this->expectException(TransportException::class);
$this->expectExceptionMessageMatches('/testMessage.+400: "testDescription"/');

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