koel/app/Services/ITunesService.php

46 lines
1.3 KiB
PHP
Raw Normal View History

2016-12-11 21:08:30 +08: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 18:00:59 +02:00
use Illuminate\Cache\Repository as Cache;
2016-12-11 21:08:30 +08:00
2022-08-08 18:00:59 +02:00
class ITunesService
2016-12-11 21:08:30 +08:00
{
public function __construct(private ITunesConnector $connector, private Cache $cache)
2022-08-08 18:00:59 +02:00
{
}
public static function used(): bool
2016-12-11 21:08:30 +08:00
{
return (bool) config('koel.itunes.enabled');
}
public function getTrackUrl(string $trackName, Album $album): ?string
2016-12-11 21:08:30 +08:00
{
return attempt(function () use ($trackName, $album): ?string {
$request = new GetTrackRequest($trackName, $album);
$hash = md5(serialize($request->query()));
2020-03-10 11:16:55 +01:00
return $this->cache->remember(
2024-03-22 16:33:18 +01:00
"itunes.track.$hash",
now()->addWeek(),
function () use ($request): ?string {
$response = $this->connector->send($request)->object();
2016-12-11 21:08:30 +08:00
2017-08-05 23:27:26 +01:00
if (!$response->resultCount) {
2018-08-24 17:27:19 +02:00
return null;
2017-08-05 23:27:26 +01:00
}
2016-12-11 21:08:30 +08:00
2017-08-05 23:27:26 +01:00
$trackUrl = $response->results[0]->trackViewUrl;
$connector = parse_url($trackUrl, PHP_URL_QUERY) ? '&' : '?';
2022-08-08 18:00:59 +02:00
2020-12-22 21:11:22 +01:00
return $trackUrl . "{$connector}at=" . config('koel.itunes.affiliate_id');
2017-08-05 23:27:26 +01:00
}
);
2022-08-08 18:00:59 +02:00
});
2018-08-19 16:40:25 +02:00
}
2016-12-11 21:08:30 +08:00
}