2016-12-11 13:08:30 +00:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace App\Services;
|
|
|
|
|
2017-08-05 22:27:26 +00:00
|
|
|
use Cache;
|
2016-12-11 13:21:45 +00:00
|
|
|
use Exception;
|
2016-12-11 13:08:30 +00:00
|
|
|
use GuzzleHttp\Client;
|
2016-12-11 13:21:45 +00:00
|
|
|
use Log;
|
2016-12-11 13:08:30 +00:00
|
|
|
|
|
|
|
class iTunes
|
|
|
|
{
|
|
|
|
/**
|
|
|
|
* @var Client
|
|
|
|
*/
|
|
|
|
protected $client;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @var string
|
|
|
|
*/
|
|
|
|
protected $endPoint = 'https://itunes.apple.com/search';
|
|
|
|
|
|
|
|
/**
|
|
|
|
* iTunes constructor.
|
|
|
|
*
|
|
|
|
* @param Client|null $client
|
|
|
|
*/
|
|
|
|
public function __construct(Client $client = null)
|
|
|
|
{
|
|
|
|
$this->client = $client ?: new Client();
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Determines whether to use iTunes services.
|
|
|
|
*
|
|
|
|
* @return bool
|
|
|
|
*/
|
|
|
|
public function used()
|
|
|
|
{
|
|
|
|
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
|
|
|
|
*/
|
|
|
|
public function getTrackUrl($term, $album = '', $artist = '')
|
|
|
|
{
|
2016-12-11 13:21:45 +00:00
|
|
|
try {
|
2017-08-05 22:27:26 +00:00
|
|
|
return Cache::remember(md5("itunes_track_url_{$term}{$album}{$artist}"), 24 * 60 * 7,
|
|
|
|
function () use ($term, $album, $artist) {
|
|
|
|
$params = [
|
|
|
|
'term' => $term.($album ? " $album" : '').($artist ? " $artist" : ''),
|
|
|
|
'media' => 'music',
|
|
|
|
'entity' => 'song',
|
|
|
|
'limit' => 1,
|
|
|
|
];
|
2016-12-11 13:08:30 +00:00
|
|
|
|
2017-08-05 22:27:26 +00:00
|
|
|
$response = (string) $this->client->get($this->endPoint, ['query' => $params])->getBody();
|
|
|
|
$response = json_decode($response);
|
2016-12-11 13:08:30 +00:00
|
|
|
|
2017-08-05 22:27:26 +00:00
|
|
|
if (!$response->resultCount) {
|
|
|
|
return false;
|
|
|
|
}
|
2016-12-11 13:08:30 +00:00
|
|
|
|
2017-08-05 22:27:26 +00:00
|
|
|
$trackUrl = $response->results[0]->trackViewUrl;
|
2016-12-11 13:21:45 +00:00
|
|
|
|
2017-08-05 22:27:26 +00:00
|
|
|
if (parse_url($trackUrl, PHP_URL_QUERY)) {
|
|
|
|
$trackUrl .= '&at='.config('koel.itunes.affiliate_id');
|
|
|
|
} else {
|
|
|
|
$trackUrl .= '?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);
|
|
|
|
|
|
|
|
return false;
|
|
|
|
}
|
2016-12-11 13:08:30 +00:00
|
|
|
}
|
|
|
|
}
|