diff --git a/app/Services/iTunes.php b/app/Services/iTunes.php index 4cd79ca8..9518587a 100644 --- a/app/Services/iTunes.php +++ b/app/Services/iTunes.php @@ -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; } } diff --git a/tests/iTunesTest.php b/tests/iTunesTest.php index ac093505..48c6642b 100644 --- a/tests/iTunesTest.php +++ b/tests/iTunesTest.php @@ -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'))); } }