koel/app/Services/iTunesService.php

73 lines
2.1 KiB
PHP
Raw Normal View History

2016-12-11 13:08:30 +00:00
<?php
namespace App\Services;
2016-12-11 13:21:45 +00:00
use Exception;
2016-12-11 13:08:30 +00:00
2019-04-07 21:09:25 +00:00
class iTunesService extends AbstractApiClient implements ApiConsumerInterface
2016-12-11 13:08:30 +00:00
{
/**
* Determines whether to use iTunes services.
*/
2018-08-24 15:27:19 +00:00
public 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.
*
2018-09-03 12:42:37 +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
{
2016-12-11 13:21:45 +00:00
try {
2018-08-29 07:05:24 +00:00
return $this->cache->remember(md5("itunes_track_url_{$term}{$album}{$artist}"), 24 * 60 * 7,
function () use ($term, $album, $artist): ?string {
2017-08-05 22:27:26 +00:00
$params = [
'term' => $term.($album ? " $album" : '').($artist ? " $artist" : ''),
'media' => 'music',
'entity' => 'song',
'limit' => 1,
];
2016-12-11 13:08:30 +00:00
2018-08-24 15:27:19 +00:00
$response = json_decode(
$this->getClient()->get($this->getEndpoint(), ['query' => $params])->getBody()
);
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) ? '&' : '?';
$trackUrl .= "{$connector}at=".config('koel.itunes.affiliate_id');
2016-12-11 13:08:30 +00:00
2017-08-05 22:27:26 +00:00
return $trackUrl;
}
);
2016-12-11 13:21:45 +00:00
} catch (Exception $e) {
2018-08-31 13:47:15 +00:00
$this->logger->error($e);
2016-12-11 13:21:45 +00:00
2018-08-24 15:27:19 +00:00
return null;
2016-12-11 13:21:45 +00:00
}
2016-12-11 13:08:30 +00:00
}
2018-08-19 14:40:25 +00:00
2018-08-24 15:27:19 +00:00
public function getKey(): ?string
2018-08-19 14:40:25 +00:00
{
2018-08-24 15:27:19 +00:00
return null;
2018-08-19 14:40:25 +00:00
}
2018-08-24 15:27:19 +00:00
public function getSecret(): ?string
2018-08-19 14:40:25 +00:00
{
2018-08-24 15:27:19 +00:00
return null;
2018-08-19 14:40:25 +00:00
}
2018-08-29 10:36:05 +00:00
public function getEndpoint(): ?string
2018-08-19 14:40:25 +00:00
{
return config('koel.itunes.endpoint');
}
2016-12-11 13:08:30 +00:00
}