Files
wticreatorstudio/Modules/Livestream/Services/Restream.php
2024-04-25 16:48:43 +08:00

93 lines
2.7 KiB
PHP

<?php
namespace Modules\Livestream\Services;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Str;
use Modules\Livestream\Entities\RestreamSetting;
use Modules\Livestream\Entities\RestreamToken;
class Restream
{
protected $base_url = 'https://api.restream.io';
public $client_id;
public $client_secret;
public function __construct()
{
$settings = RestreamSetting::first();
if ($settings) {
$this->client_id = $settings->client_id;
$this->client_secret = $settings->client_secret;
}
}
public function connect()
{
$redirectUri = route('restream.callback');
$stateToken = Str::random();
session(['state-token' => $stateToken]);
$url = "{$this->base_url}/login?response_type=code&client_id={$this->client_id}&redirect_uri={$redirectUri}&state={$stateToken}";
return Redirect::away($url);
}
public function exchange($code)
{
try {
$client = new Client();
$response = $client->post("{$this->base_url}/oauth/token", [
'form_params' => [
'grant_type' => 'authorization_code',
'redirect_uri' => route('restream.callback'),
'code' => $code,
'client_id' => $this->client_id,
'client_secret' => $this->client_secret,
],
]);
$status = $response->getStatusCode();
$data = json_decode($response->getBody());
if ($status == 200) {
$item = RestreamToken::updateOrCreate([ 'client_id' => $this->client_id ], [
'access_token' => $data->access_token,
'refresh_token' => $data->refresh_token,
'scope' => json_encode($data->scope),
'type' => $data->token_type,
]);
Log::info('Restream Connected');
return true;
} else {
Log::info("Status code: {$status}");
Log::info("Message: {$data->message}");
}
} catch (ClientException $exception) {
}
return false;
}
public function isConnected()
{
$token = RestreamToken::first();
if ($token) {
return true;
}
return false;
}
public function updateSettings($clientId, $clientSecret)
{
RestreamSetting::truncate();
RestreamSetting::updateOrCreate([ 'client_id' => $clientId ], [ 'client_secret' => $clientSecret ]);
}
}