Skip to content

Instantly share code, notes, and snippets.

@thybzi
Created February 27, 2019 19:04
Show Gist options
  • Save thybzi/d5fcc2004ae4d99ac4dc65b13165e56d to your computer and use it in GitHub Desktop.
Save thybzi/d5fcc2004ae4d99ac4dc65b13165e56d to your computer and use it in GitHub Desktop.
<?php
ini_set('user_agent', 'ThybziDiscogsClient/1.1 +http://thybzi.com/wishlist');
define('BASE_URI', 'https://api.discogs.com/');
define('API_TOKEN', 'YOUR_TOKEN_HERE'); // get one on https://www.discogs.com/settings/developers
define('CACHE_DIR', __DIR__ . '/../cache/');
define('CACHE_LIFE', 24 * 60 * 60);
define('PER_PAGE', 100);
function getUriContent($uri) {
$context = stream_context_create([
'http' => [
'method' => 'GET',
'header' => 'Authorization: Discogs token=' . API_TOKEN . "\r\n",
]
]);
if (strpos($uri, 'http') !== 0) {
$uri = BASE_URI . $uri;
}
return file_get_contents($uri, false, $context);
}
function getPaginatedUriContent($uri) {
$data = [];
$next_page_uri = $uri . '?' . http_build_query(['per_page' => PER_PAGE]);
while (!is_null($next_page_uri)) {
$content = getUriContent($next_page_uri);
$data = array_merge_recursive($data, json_decode($content, true));
if (isset($data['pagination'])) {
$next_page_uri = isset($data['pagination']['urls']['next']) ?
$data['pagination']['urls']['next'] :
null;
unset($data['pagination']);
} else {
$next_page_uri = null;
}
}
return json_encode($data);
}
function getCacheFilePath($cmd, $id) {
return CACHE_DIR . $cmd . (is_null($id) ? '' : "_$id") . '.json';
}
function getCommand($cmd, $id) {
$cachefile_path = getCacheFilePath($cmd, $id);
if (file_exists($cachefile_path) && filemtime($cachefile_path) >= (time() - CACHE_LIFE)) {
return file_get_contents($cachefile_path);
}
switch ($cmd) {
case 'wantlist':
$content = getPaginatedUriContent('users/thybzi/wants');
break;
case 'collection':
$content = getPaginatedUriContent('users/thybzi/collection/folders/0/releases');
break;
case 'master':
$content = getUriContent('masters/' . $id);
break;
}
file_put_contents($cachefile_path, $content);
return $content;
}
$cmd = isset($_GET['cmd']) ? $_GET['cmd'] : 'wantlist';
if (in_array($cmd, ['wantlist', 'collection', 'master'])) {
$id = isset($_GET['id']) ? $_GET['id'] : NULL;
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
echo getCommand($cmd, $id);
} else {
die('Unknown command: ' . $cmd);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment