koel/app/Services/Lastfm.php

335 lines
8.9 KiB
PHP
Raw Normal View History

<?php
namespace App\Services;
2016-04-02 13:16:09 +00:00
use Exception;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Cache;
use Log;
class Lastfm extends RESTfulService
{
/**
* Specify the response format, since Last.fm only returns XML.
2016-03-06 04:11:28 +00:00
*
* @var string
*/
protected $responseFormat = 'xml';
/**
* Override the key param, since, again, Lastfm wants to be different.
2016-03-06 04:11:28 +00:00
*
* @var string
*/
protected $keyParam = 'api_key';
/**
* Construct an instance of Lastfm service.
2016-03-06 04:11:28 +00:00
*
* @param string $key Last.fm API key.
* @param string $secret Last.fm API shared secret.
* @param Client $client The Guzzle HTTP client.
*/
public function __construct($key = null, $secret = null, Client $client = null)
{
parent::__construct(
2016-08-21 15:19:03 +00:00
$key ?: config('koel.lastfm.key'),
$secret ?: config('koel.lastfm.secret'),
'https://ws.audioscrobbler.com/2.0',
$client ?: new Client()
);
}
2016-06-05 04:37:03 +00:00
/**
* Determine if our application is using Last.fm.
*
* @return bool
*/
public function used()
{
2016-08-21 15:19:03 +00:00
return config('koel.lastfm.key') && config('koel.lastfm.secret');
2016-06-05 04:37:03 +00:00
}
2015-12-20 12:17:35 +00:00
/**
* Determine if Last.fm integration is enabled.
*
* @return bool
*/
public function enabled()
{
return $this->getKey() && $this->getSecret();
}
/**
* Get information about an artist.
2016-03-06 04:11:28 +00:00
*
* @param $name string Name of the artist
*
2016-08-03 10:42:11 +00:00
* @return array|false
*/
public function getArtistInfo($name)
{
if (!$this->enabled()) {
return false;
}
$name = urlencode($name);
try {
$cacheKey = md5("lastfm_artist_$name");
2016-12-12 02:43:14 +00:00
if ($response = cache($cacheKey)) {
$response = simplexml_load_string($response);
} else {
if ($response = $this->get("?method=artist.getInfo&autocorrect=1&artist=$name")) {
2016-12-12 02:43:14 +00:00
cache([$cacheKey => $response->asXML()], 24 * 60 * 7);
}
}
$response = json_decode(json_encode($response), true);
if (!$response || !$artist = array_get($response, 'artist')) {
return false;
}
return [
'url' => array_get($artist, 'url'),
'image' => count($artist['image']) > 3 ? $artist['image'][3] : $artist['image'][0],
'bio' => [
'summary' => $this->formatText(array_get($artist, 'bio.summary')),
'full' => $this->formatText(array_get($artist, 'bio.content')),
],
];
2016-04-02 13:16:09 +00:00
} catch (Exception $e) {
Log::error($e);
return false;
}
}
/**
* Get information about an album.
2016-03-06 04:11:28 +00:00
*
* @param string $name Name of the album
* @param string $artistName Name of the artist
2016-03-06 04:11:28 +00:00
*
* @return array|false
*/
public function getAlbumInfo($name, $artistName)
{
if (!$this->enabled()) {
return false;
}
$name = urlencode($name);
$artistName = urlencode($artistName);
try {
$cacheKey = md5("lastfm_album_{$name}_{$artistName}");
2016-12-12 02:43:14 +00:00
if ($response = cache($cacheKey)) {
$response = simplexml_load_string($response);
} else {
if ($response = $this->get("?method=album.getInfo&autocorrect=1&album=$name&artist=$artistName")) {
2016-12-12 02:43:14 +00:00
cache([$cacheKey => $response->asXML()], 24 * 60 * 7);
}
}
$response = json_decode(json_encode($response), true);
if (!$response || !$album = array_get($response, 'album')) {
return false;
}
return [
'url' => array_get($album, 'url'),
'image' => count($album['image']) > 3 ? $album['image'][3] : $album['image'][0],
'wiki' => [
'summary' => $this->formatText(array_get($album, 'wiki.summary')),
'full' => $this->formatText(array_get($album, 'wiki.content')),
],
'tracks' => array_map(function ($track) {
return [
'title' => $track['name'],
'length' => (int) $track['duration'],
'url' => $track['url'],
];
}, array_get($album, 'tracks.track', [])),
];
2016-04-02 13:16:09 +00:00
} catch (Exception $e) {
Log::error($e);
return false;
}
}
/**
2015-12-20 12:17:35 +00:00
* Get Last.fm's session key for the authenticated user using a token.
2016-03-06 04:11:28 +00:00
*
2015-12-20 12:17:35 +00:00
* @param string $token The token after successfully connecting to Last.fm
*
2015-12-20 12:17:35 +00:00
* @link http://www.last.fm/api/webauth#4
2016-03-06 04:11:28 +00:00
*
2015-12-20 12:17:35 +00:00
* @return string The token key
*/
public function getSessionKey($token)
{
$query = $this->buildAuthCallParams([
'method' => 'auth.getSession',
'token' => $token,
], true);
try {
$response = $this->get("/?$query", [], false);
return (string) $response->session->key;
2016-04-02 13:16:09 +00:00
} catch (Exception $e) {
2015-12-20 12:17:35 +00:00
Log::error($e);
return false;
}
}
/**
* Scrobble a song.
2016-03-06 04:11:28 +00:00
*
2015-12-20 12:17:35 +00:00
* @param string $artist The artist name
* @param string $track The track name
* @param string|int $timestamp The UNIX timestamp
* @param string $album The album name
* @param string $sk The session key
2016-03-06 04:11:28 +00:00
*
* @return bool
*/
2015-12-21 13:49:00 +00:00
public function scrobble($artist, $track, $timestamp, $album, $sk)
{
2015-12-21 13:49:00 +00:00
$params = compact('artist', 'track', 'timestamp', 'sk');
2015-12-20 12:17:35 +00:00
if ($album) {
$params['album'] = $album;
}
$params['method'] = 'track.scrobble';
try {
2015-12-20 12:30:28 +00:00
return (bool) $this->post('/', $this->buildAuthCallParams($params), false);
2016-04-02 13:16:09 +00:00
} catch (Exception $e) {
2015-12-20 12:17:35 +00:00
Log::error($e);
return false;
}
}
2015-12-21 13:49:00 +00:00
/**
* Love or unlove a track on Last.fm.
2016-03-06 04:11:28 +00:00
*
2015-12-21 13:50:26 +00:00
* @param string $track The track name
* @param string $artist The artist's name
* @param string $sk The session key
* @param bool $love Whether to love or unlove. Such cheesy terms... urrgggh
2016-03-06 04:11:28 +00:00
*
2015-12-21 13:49:00 +00:00
* @return bool
*/
public function toggleLoveTrack($track, $artist, $sk, $love = true)
{
$params = compact('track', 'artist', 'sk');
$params['method'] = $love ? 'track.love' : 'track.unlove';
try {
return (bool) $this->post('/', $this->buildAuthCallParams($params), false);
2016-04-02 13:16:09 +00:00
} catch (Exception $e) {
2015-12-21 13:49:00 +00:00
Log::error($e);
return false;
}
}
2015-12-23 06:26:16 +00:00
/**
* Update a track's "now playing" on Last.fm.
2016-03-06 04:11:28 +00:00
*
2015-12-23 06:26:16 +00:00
* @param string $artist Name of the artist
* @param string $track Name of the track
* @param string $album Name of the album
* @param int|float $duration Duration of the track, in seconds
* @param string $sk The session key
2016-03-06 04:11:28 +00:00
*
2015-12-23 06:26:16 +00:00
* @return bool
*/
public function updateNowPlaying($artist, $track, $album, $duration, $sk)
{
$params = compact('artist', 'track', 'duration', 'sk');
$params['method'] = 'track.updateNowPlaying';
if ($album) {
$params['album'] = $album;
}
try {
return (bool) $this->post('/', $this->buildAuthCallParams($params), false);
2016-04-02 13:16:09 +00:00
} catch (Exception $e) {
2015-12-23 06:26:16 +00:00
Log::error($e);
return false;
}
}
2015-12-20 12:17:35 +00:00
/**
* Build the parameters to use for _authenticated_ Last.fm API calls.
* Such calls require:
* - The API key (api_key)
* - The API signature (api_sig).
*
* @link http://www.last.fm/api/webauth#5
2016-03-06 04:11:28 +00:00
*
2015-12-20 12:17:35 +00:00
* @param array $params The array of parameters.
* @param bool $toString Whether to turn the array into a query string
*
* @return array|string
*/
public function buildAuthCallParams(array $params, $toString = false)
{
$params['api_key'] = $this->getKey();
ksort($params);
// Generate the API signature.
// @link http://www.last.fm/api/webauth#6
$str = '';
foreach ($params as $name => $value) {
$str .= $name.$value;
}
$str .= $this->getSecret();
$params['api_sig'] = md5($str);
if (!$toString) {
return $params;
}
$query = '';
foreach ($params as $key => $value) {
$query .= "$key=$value&";
}
return rtrim($query, '&');
}
/**
* Correctly format a string returned by Last.fm.
2016-03-06 04:11:28 +00:00
*
2015-12-20 12:17:35 +00:00
* @param string $str
2016-03-06 04:11:28 +00:00
*
2015-12-20 12:17:35 +00:00
* @return string
*/
protected function formatText($str)
{
if (!$str) {
return '';
}
return trim(str_replace('Read more on Last.fm', '', nl2br(strip_tags(html_entity_decode($str)))));
}
}