Skip to content

Instantly share code, notes, and snippets.

@codebucketdev
Last active April 9, 2017 17:40
Show Gist options
  • Save codebucketdev/044e4c9501b7f6c5f7d86f2fe0496b75 to your computer and use it in GitHub Desktop.
Save codebucketdev/044e4c9501b7f6c5f7d86f2fe0496b75 to your computer and use it in GitHub Desktop.
❤️
<?php
use CoverArtArchive\CoverArt;
use Guzzle\Http\Client;
use MusicBrainz\Filters\RecordingFilter;
use MusicBrainz\HttpAdapters\GuzzleHttpAdapter;
use MusicBrainz\MusicBrainz;
use phpFastCache\CacheManager;
use Ramsey\Uuid\Uuid;
class ArtworkFetcher {
/**
*
* @var ArtworkFetcher
*/
private static $instance;
public static function getInstance() {
if (is_null(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
private $brainz;
private $cache;
private $expireAt;
private function __construct() {
$this->brainz = new MusicBrainz(new GuzzleHttpAdapter(new Client()));
$this->brainz->setUserAgent("python-musicbrainz", "2.0", "http://coverart.codebucket.de");
$this->cache = CacheManager::getInstance("predis", [
'host' => '127.0.0.1',
'fallback' => 'files',
'path' => dirname(__FILE__) . '/cache'
]);
$this->expireAt = new DateTime(date('Y-m-d H:i:s', strtotime('+1 month', time())));
}
public function getTrackId($track, $artist) {
$uuid = Uuid::uuid3(Uuid::NAMESPACE_DNS, $track . ":" . $artist);
$key = "track:" . $uuid->toString();
// cache lookup
if ($this->cache->hasItem($key)) {
return $this->readCache($key);
}
$filter = array(
"artist" => urlencode($artist),
"recording" => urlencode($track)
);
$recordings = $this->brainz->search(new RecordingFilter($filter));
$mbid = $recordings[0]->id;
$this->writeCache($key, $mbid);
return $mbid;
}
public function getCover($mbid) {
$key = "cover:" . $mbid;
// cache lookup
if ($this->cache->hasItem($key)) {
return $this->readCache($key);
}
$recordings = $this->brainz->lookup("recording", $mbid, array("releases"));
$releases = $recordings['releases'];
// remove unofficial releases without date
foreach ($releases as $item => $release) {
if (!isset($release['date'])) {
unset($releases[$item]);
}
}
usort($releases, function($a, $b) {
return strtotime($a['date']) - strtotime($b['date']); // $y - $x to reverse direction
});
$release = $releases[0];
$coverart = new CoverArt($release['id'], new Client());
$cover = (array) $coverart->front;
$this->writeCache($key, $cover);
return $cover;
}
private function readCache($key) {
$item = $this->cache->getItem($key);
return $item->get();
}
private function writeCache($key, $value) {
$item = $this->cache->getItem($key);
$now = new DateTime(date('Y-m-d H:i:s', time()));
$diff = $now->diff($this->expireAt);
$item->set($value)->expiresAfter($diff);
$this->cache->save($item);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment