forked from symfony/firebase-notifier
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFirebaseTransport.php
More file actions
161 lines (137 loc) · 5.76 KB
/
FirebaseTransport.php
File metadata and controls
161 lines (137 loc) · 5.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
<?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 Google\Client;
use Google\Service\FirebaseCloudMessaging;
use Symfony\Component\Notifier\Exception\InvalidArgumentException;
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\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\DecodingExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
/**
* @author Jeroen Spee <https://github.com/Jeroeny>
*/
final class FirebaseTransport extends AbstractTransport
{
protected const HOST = 'fcm.googleapis.com/v1/projects/';
protected string $projectId;
public function __construct(
?HttpClientInterface $client = null,
?EventDispatcherInterface $dispatcher = null,
)
{
parent::__construct($client, $dispatcher);
}
public function __toString(): string
{
return sprintf('firebase://%s', $this->getEndpoint());
}
public function supports(MessageInterface $message): bool
{
return $message instanceof ChatMessage && (null === $message->getOptions() || $message->getOptions() instanceof FirebaseOptions);
}
public function getProjectId(): string
{
return $this->projectId;
}
public function setProjectId($projectId): self
{
$this->projectId = $projectId;
return $this;
}
protected function getEndpoint(): string
{
return ($this->host ?: $this->getDefaultHost()) . ($this->projectId ?: '') . '/messages:send';
}
/**
* @throws DecodingExceptionInterface
* @throws ClientExceptionInterface
* @throws ServerExceptionInterface
* @throws RedirectionExceptionInterface
* @throws TransportExceptionInterface
*/
protected function doSend(MessageInterface $message): SentMessage
{
if (!$message instanceof ChatMessage) {
throw new UnsupportedMessageTypeException(__CLASS__, ChatMessage::class, $message);
}
$endpoint = sprintf('https://%s', $this->getEndpoint());
$options = $message->getOptions()?->toArray() ?? [];
$validateOnly = false;
if (!$options['topic']) {
throw new InvalidArgumentException(sprintf('The "%s" transport required the "topic" option to be set.', __CLASS__));
}
// Unset notification from options if we do not want to send them at all - cannot be empty array nor null
if (!$options['notification']['sendNotification']) {
unset($options['notification']);
} else {
if (isset($options['notification']['validate_only'])) {
$validateOnly = $options['notification']['validate_only'];
unset($options['notification']['validate_only']);
}
$options['notification']['body'] = $message->getSubject();
}
if (empty($options['data'])) {
unset($options['data']);
}
$options = ['message' => $options, 'validate_only' => $validateOnly];
$response = $this->client->request('POST', $endpoint, [
'headers' => [
'Authorization' => sprintf('Bearer %s', $this->getAccessToken()),
'Content-Type' => 'application/json; UTF-8'
],
'json' => array_filter($options)
]);
try {
$statusCode = $response->getStatusCode();
} catch (TransportExceptionInterface $e) {
throw new TransportException('Could not reach the remote Firebase server.', $response, 0, $e);
}
$contentType = $response->getHeaders(false)['content-type'][0] ?? '';
$jsonContents = str_starts_with($contentType, 'application/json') ? $response->toArray(false) : null;
$errorMessage = null;
if ($jsonContents && isset($jsonContents['error']['message'])) {
$errorMessage = $jsonContents['error']['message'];
} elseif (200 !== $statusCode) {
$errorMessage = $response->getContent(false);
}
if (null !== $errorMessage) {
throw new TransportException('Unable to post the Firebase message: ' . $errorMessage, $response);
}
$success = $response->toArray(false);
$messageId = isset($success['name']) ? basename($success['name'], '/') : '';
$sentMessage = new SentMessage($message, (string)$this);
$sentMessage->setMessageId($messageId);
return $sentMessage;
}
/**
* Create a temporary json file from the ENV variable and set it to the client auth config
* @return string|null
*/
protected function getAccessToken(): ?string
{
$client = new Client();
$client->useApplicationDefaultCredentials();
$client->addScope(FirebaseCloudMessaging::FIREBASE_MESSAGING);
$client->addScope(FirebaseCloudMessaging::CLOUD_PLATFORM);
$client->fetchAccessTokenWithAssertion();
$accessToken = $client->getAccessToken();
return $accessToken['access_token'] ?? null;
}
}