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;
|
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
|
|
|
{
|
2024-03-22 15:22:29 +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');
|
|
|
|
}
|
|
|
|
|
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-03-22 15:22:29 +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(
|
2024-03-22 15:22:29 +00:00
|
|
|
"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;
|
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
|
|
|
}
|