2016-12-11 13:08:30 +00:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace App\Services;
|
|
|
|
|
2024-03-22 15:22:29 +00:00
|
|
|
use App\Http\Integrations\iTunes\ITunesConnector;
|
|
|
|
use App\Http\Integrations\iTunes\Requests\GetTrackRequest;
|
|
|
|
use App\Models\Album;
|
2024-06-04 13:35:00 +00:00
|
|
|
use Illuminate\Support\Facades\Cache;
|
2016-12-11 13:08:30 +00:00
|
|
|
|
2022-08-08 16:00:59 +00:00
|
|
|
class ITunesService
|
2016-12-11 13:08:30 +00:00
|
|
|
{
|
2024-06-04 13:35:00 +00:00
|
|
|
public function __construct(private readonly ITunesConnector $connector)
|
2022-08-08 16:00:59 +00:00
|
|
|
{
|
|
|
|
}
|
|
|
|
|
|
|
|
public static function used(): bool
|
2016-12-11 13:08:30 +00:00
|
|
|
{
|
|
|
|
return (bool) config('koel.itunes.enabled');
|
|
|
|
}
|
|
|
|
|
2024-03-22 15:22:29 +00:00
|
|
|
public function getTrackUrl(string $trackName, Album $album): ?string
|
2016-12-11 13:08:30 +00:00
|
|
|
{
|
2024-09-30 22:15:38 +00:00
|
|
|
return rescue(function () use ($trackName, $album): ?string {
|
2024-03-22 15:22:29 +00:00
|
|
|
$request = new GetTrackRequest($trackName, $album);
|
|
|
|
$hash = md5(serialize($request->query()));
|
|
|
|
|
2024-06-04 13:35:00 +00:00
|
|
|
return Cache::remember(
|
2024-03-22 15:33:18 +00:00
|
|
|
"itunes.track.$hash",
|
2024-03-22 15:22:29 +00:00
|
|
|
now()->addWeek(),
|
|
|
|
function () use ($request): ?string {
|
|
|
|
$response = $this->connector->send($request)->object();
|
2016-12-11 13:08:30 +00:00
|
|
|
|
2017-08-05 22:27:26 +00:00
|
|
|
if (!$response->resultCount) {
|
2018-08-24 15:27:19 +00:00
|
|
|
return null;
|
2017-08-05 22:27:26 +00:00
|
|
|
}
|
2016-12-11 13:08:30 +00:00
|
|
|
|
2017-08-05 22:27:26 +00:00
|
|
|
$trackUrl = $response->results[0]->trackViewUrl;
|
2017-12-09 18:34:27 +00:00
|
|
|
$connector = parse_url($trackUrl, PHP_URL_QUERY) ? '&' : '?';
|
2022-08-08 16:00:59 +00:00
|
|
|
|
2020-12-22 20:11:22 +00:00
|
|
|
return $trackUrl . "{$connector}at=" . config('koel.itunes.affiliate_id');
|
2017-08-05 22:27:26 +00:00
|
|
|
}
|
|
|
|
);
|
2022-08-08 16:00:59 +00:00
|
|
|
});
|
2018-08-19 14:40:25 +00:00
|
|
|
}
|
2016-12-11 13:08:30 +00:00
|
|
|
}
|