koel/app/Services/ITunesService.php

46 lines
1.3 KiB
PHP
Raw Normal View History

2016-12-11 13:08:30 +00:00
<?php
namespace App\Services;
use App\Http\Integrations\iTunes\ITunesConnector;
use App\Http\Integrations\iTunes\Requests\GetTrackRequest;
use App\Models\Album;
2022-08-08 16:00:59 +00:00
use Illuminate\Cache\Repository as 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
{
public function __construct(private ITunesConnector $connector, private Cache $cache)
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');
}
public function getTrackUrl(string $trackName, Album $album): ?string
2016-12-11 13:08:30 +00:00
{
return attempt(function () use ($trackName, $album): ?string {
$request = new GetTrackRequest($trackName, $album);
$hash = md5(serialize($request->query()));
2020-03-10 10:16:55 +00:00
return $this->cache->remember(
"itunes:track:$hash",
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;
$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
}