2016-12-11 13:08:30 +00:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace App\Services;
|
|
|
|
|
2022-08-08 16:00:59 +00:00
|
|
|
use App\Services\ApiClients\ITunesClient;
|
|
|
|
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
|
|
|
{
|
2022-08-08 16:00:59 +00:00
|
|
|
public function __construct(private ITunesClient $client, private Cache $cache)
|
|
|
|
{
|
|
|
|
}
|
|
|
|
|
2016-12-11 13:08:30 +00:00
|
|
|
/**
|
|
|
|
* Determines whether to use iTunes services.
|
|
|
|
*/
|
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');
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Search for a track on iTunes Store with the given information and get its URL.
|
|
|
|
*
|
2021-06-05 10:47:56 +00:00
|
|
|
* @param string $term The main query string (should be the track's name)
|
|
|
|
* @param string $album The album's name, if available
|
2018-09-03 12:41:49 +00:00
|
|
|
* @param string $artist The artist's name, if available
|
2016-12-11 13:08:30 +00:00
|
|
|
*/
|
2018-08-24 15:27:19 +00:00
|
|
|
public function getTrackUrl(string $term, string $album = '', string $artist = ''): ?string
|
2016-12-11 13:08:30 +00:00
|
|
|
{
|
2022-08-08 16:00:59 +00:00
|
|
|
return attempt(function () use ($term, $album, $artist): ?string {
|
2020-03-10 10:16:55 +00:00
|
|
|
return $this->cache->remember(
|
2021-06-05 10:47:56 +00:00
|
|
|
md5("itunes_track_url_$term$album$artist"),
|
2020-03-10 10:16:55 +00:00
|
|
|
24 * 60 * 7,
|
2018-09-03 12:41:49 +00:00
|
|
|
function () use ($term, $album, $artist): ?string {
|
2017-08-05 22:27:26 +00:00
|
|
|
$params = [
|
2020-12-22 20:11:22 +00:00
|
|
|
'term' => $term . ($album ? " $album" : '') . ($artist ? " $artist" : ''),
|
2017-08-05 22:27:26 +00:00
|
|
|
'media' => 'music',
|
|
|
|
'entity' => 'song',
|
|
|
|
'limit' => 1,
|
|
|
|
];
|
2016-12-11 13:08:30 +00:00
|
|
|
|
2022-08-08 16:00:59 +00:00
|
|
|
$response = $this->client->get('/', ['query' => $params]);
|
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
|
|
|
}
|