2022-07-18 11:00:37 +00:00
|
|
|
<?php
|
|
|
|
|
2024-03-22 15:33:04 +00:00
|
|
|
namespace App\Http\Integrations\Spotify;
|
2022-07-18 11:00:37 +00:00
|
|
|
|
|
|
|
use App\Exceptions\SpotifyIntegrationDisabledException;
|
2022-08-08 16:00:59 +00:00
|
|
|
use App\Services\SpotifyService;
|
2022-07-18 11:00:37 +00:00
|
|
|
use Illuminate\Cache\Repository as Cache;
|
|
|
|
use SpotifyWebAPI\Session;
|
|
|
|
use SpotifyWebAPI\SpotifyWebAPI;
|
|
|
|
|
|
|
|
/**
|
2022-07-27 15:32:36 +00:00
|
|
|
* @method array search(string $keywords, string|array $type, array|object $options = [])
|
2022-07-18 11:00:37 +00:00
|
|
|
*/
|
|
|
|
class SpotifyClient
|
|
|
|
{
|
2024-04-18 14:36:28 +00:00
|
|
|
public function __construct(
|
|
|
|
public SpotifyWebAPI $wrapped,
|
|
|
|
private readonly ?Session $session,
|
|
|
|
private readonly Cache $cache
|
|
|
|
) {
|
2022-07-18 11:00:37 +00:00
|
|
|
if (SpotifyService::enabled()) {
|
|
|
|
$this->wrapped->setOptions(['return_assoc' => true]);
|
2022-08-08 16:00:59 +00:00
|
|
|
attempt(fn () => $this->setAccessToken());
|
2022-07-18 11:00:37 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
private function setAccessToken(): void
|
|
|
|
{
|
|
|
|
$token = $this->cache->get('spotify.access_token');
|
|
|
|
|
|
|
|
if (!$token) {
|
|
|
|
$this->session->requestCredentialsToken();
|
|
|
|
$token = $this->session->getAccessToken();
|
|
|
|
|
|
|
|
// Spotify's tokens expire after 1 hour, so we'll cache them with some buffer to an extra call.
|
|
|
|
$this->cache->put('spotify.access_token', $token, 59 * 60);
|
|
|
|
}
|
|
|
|
|
|
|
|
$this->wrapped->setAccessToken($token);
|
|
|
|
}
|
|
|
|
|
|
|
|
public function __call(string $name, array $arguments): mixed
|
|
|
|
{
|
|
|
|
throw_unless(SpotifyService::enabled(), SpotifyIntegrationDisabledException::create());
|
|
|
|
|
|
|
|
return $this->wrapped->$name(...$arguments);
|
|
|
|
}
|
|
|
|
}
|