koel/app/Services/ITunesService.php

58 lines
1.8 KiB
PHP
Raw Normal View History

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
* @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,
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;
$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
}