koel/app/Services/iTunesService.php

86 lines
2.3 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;
2018-08-29 07:05:24 +00:00
use GuzzleHttp\Client;
use Illuminate\Contracts\Cache\Repository as Cache;
2016-12-11 13:21:45 +00:00
use Log;
2016-12-11 13:08:30 +00:00
2018-08-19 14:40:25 +00:00
class iTunesService extends ApiClient implements ApiConsumerInterface
2016-12-11 13:08:30 +00:00
{
2018-08-29 07:05:24 +00:00
private $cache;
public function __construct(Client $client, Cache $cache)
{
parent::__construct($client);
$this->cache = $cache;
}
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.
*
* @param $term string The main query string (should be the track's name)
* @param $album string The album's name, if available
* @param $artist string The artist's name, if available
*
* @return string|false
*/
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) {
Log::error($e);
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-24 15:27:19 +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
}