| 1 |
<?php |
| 2 |
|
| 3 |
namespace MediaWiki\Extension\Notifications\Push; |
| 4 |
|
| 5 |
use MediaWiki\Http\HttpRequestFactory; |
| 6 |
use MediaWiki\Status\Status; |
| 7 |
use MWHttpRequest; |
| 8 |
use Psr\Log\LoggerAwareInterface; |
| 9 |
use Psr\Log\LoggerAwareTrait; |
| 10 |
|
| 11 |
class NotificationServiceClient implements LoggerAwareInterface { |
| 12 |
|
| 13 |
use LoggerAwareTrait; |
| 14 |
|
| 15 |
|
| 16 |
private $httpRequestFactory; |
| 17 |
|
| 18 |
|
| 19 |
private $endpointBase; |
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
public function __construct( HttpRequestFactory $httpRequestFactory, string $endpointBase ) { |
| 26 |
$this->httpRequestFactory = $httpRequestFactory; |
| 27 |
$this->endpointBase = $endpointBase; |
| 28 |
} |
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
public function sendCheckEchoRequests( array $subscriptions ): void { |
| 36 |
$tokenMap = []; |
| 37 |
foreach ( $subscriptions as $subscription ) { |
| 38 |
$provider = $subscription->getProvider(); |
| 39 |
$topic = $subscription->getTopic() ?? 0; |
| 40 |
if ( !isset( $tokenMap[$topic][$provider] ) ) { |
| 41 |
$tokenMap[$topic][$provider] = []; |
| 42 |
} |
| 43 |
|
| 44 |
$tokenMap[$topic][$provider][] = $subscription->getToken(); |
| 45 |
} |
| 46 |
foreach ( $tokenMap as $topic => $providerMap ) { |
| 47 |
foreach ( $providerMap as $provider => $tokens ) { |
| 48 |
$payload = [ |
| 49 |
'deviceTokens' => $tokens, |
| 50 |
'messageType' => 'checkEchoV1' |
| 51 |
]; |
| 52 |
if ( $topic !== 0 ) { |
| 53 |
$payload['topic'] = $topic; |
| 54 |
} |
| 55 |
$this->sendRequest( $provider, $payload ); |
| 56 |
} |
| 57 |
} |
| 58 |
} |
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
|
| 64 |
|
| 65 |
protected function sendRequest( string $provider, array $payload ): void { |
| 66 |
$request = $this->constructRequest( $provider, $payload ); |
| 67 |
$status = $request->execute(); |
| 68 |
if ( !$status->isOK() ) { |
| 69 |
$errors = $status->getErrorsByType( 'error' ); |
| 70 |
$this->logger->warning( |
| 71 |
serialize( Status::wrap( $status )->getMessage( false, false, 'en' ) ), |
| 72 |
[ |
| 73 |
'error' => $errors, |
| 74 |
'caller' => __METHOD__, |
| 75 |
'content' => $request->getContent() |
| 76 |
] |
| 77 |
); |
| 78 |
} |
| 79 |
} |
| 80 |
|
| 81 |
|
| 82 |
|
| 83 |
|
| 84 |
|
| 85 |
|
| 86 |
|
| 87 |
private function constructRequest( string $provider, array $payload ): MWHttpRequest { |
| 88 |
$url = "$this->endpointBase/$provider"; |
| 89 |
$opts = [ 'method' => 'POST', 'postData' => json_encode( $payload ) ]; |
| 90 |
$req = $this->httpRequestFactory->create( $url, $opts, __METHOD__ ); |
| 91 |
$req->setHeader( 'Content-Type', 'application/json; charset=utf-8' ); |
| 92 |
return $req; |
| 93 |
} |
| 94 |
|
| 95 |
} |