mirror of
https://github.com/koel/koel
synced 2024-11-10 06:34:14 +00:00
Cache iTunes request
This commit is contained in:
parent
86ca8d40f6
commit
876db46501
2 changed files with 35 additions and 20 deletions
|
@ -2,7 +2,9 @@
|
|||
|
||||
namespace App\Services;
|
||||
|
||||
use Exception;
|
||||
use GuzzleHttp\Client;
|
||||
use Log;
|
||||
|
||||
class iTunes
|
||||
{
|
||||
|
@ -47,29 +49,40 @@ class iTunes
|
|||
*/
|
||||
public function getTrackUrl($term, $album = '', $artist = '')
|
||||
{
|
||||
$params = [
|
||||
'term' => $term.($album ? ' '.$album : '').($artist ? ' '.$artist : ''),
|
||||
'media' => 'music',
|
||||
'entity' => 'song',
|
||||
'limit' => 1,
|
||||
];
|
||||
try {
|
||||
$cacheKey = md5("itunes_track_url_{$term}{$album}{$artist}");
|
||||
if (!$trackUrl = cache($cacheKey)) {
|
||||
$params = [
|
||||
'term' => $term.($album ? ' '.$album : '').($artist ? ' '.$artist : ''),
|
||||
'media' => 'music',
|
||||
'entity' => 'song',
|
||||
'limit' => 1,
|
||||
];
|
||||
|
||||
$response = (string) $this->client->get($this->endPoint, ['query' => $params])->getBody();
|
||||
$response = json_decode($response);
|
||||
$response = (string) $this->client->get($this->endPoint, ['query' => $params])->getBody();
|
||||
$response = json_decode($response);
|
||||
|
||||
if (!$response->resultCount) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$trackUrl = $response->results[0]->trackViewUrl;
|
||||
|
||||
// Returns a string if the URL has parameters or NULL if not
|
||||
if (parse_url($trackUrl, PHP_URL_QUERY)) {
|
||||
$trackUrl .= '&at='.config('koel.itunes.affiliate_id');
|
||||
} else {
|
||||
$trackUrl .= '?at='.config('koel.itunes.affiliate_id');
|
||||
}
|
||||
|
||||
cache([$cacheKey => $trackUrl], 24 * 60 * 7);
|
||||
}
|
||||
|
||||
return $trackUrl;
|
||||
} catch (Exception $e) {
|
||||
Log::error($e);
|
||||
|
||||
if (!$response->resultCount) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$trackUrl = $response->results[0]->trackViewUrl;
|
||||
|
||||
// Returns a string if the URL has parameters or NULL if not
|
||||
if (parse_url($trackUrl, PHP_URL_QUERY)) {
|
||||
$trackUrl .= '&at='.config('koel.itunes.affiliate_id');
|
||||
} else {
|
||||
$trackUrl .= '?at='.config('koel.itunes.affiliate_id');
|
||||
}
|
||||
|
||||
return $trackUrl;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -21,5 +21,7 @@ class iTunesTest extends TestCase
|
|||
'https://itunes.apple.com/us/album/i-remember-you/id265611220?i=265611396&uo=4&at=1000lsGu',
|
||||
$api->getTrackUrl('Foo Bar')
|
||||
);
|
||||
|
||||
self::assertNotNull(cache(md5('itunes_track_url_Foo Bar')));
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue