Skip to content

Instantly share code, notes, and snippets.

@chrisjdavis
Last active April 22, 2020 18:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisjdavis/e5865914e678ed66f55a9f9c56ae2bf1 to your computer and use it in GitHub Desktop.
Save chrisjdavis/e5865914e678ed66f55a9f9c56ae2bf1 to your computer and use it in GitHub Desktop.
<?php
class EasyLASTFM
{
const ENDPOINT = 'http://ws.audioscrobbler.com/2.0/';
const URL = 'https://www.last.fm/music/';
const API_KEY = '';
const CACHETIME = '86400'; // 24 hours in seconds
private function create_dir($path) {
if ( !is_dir( $path ) ) {
mkdir( $path, 0755, true);
}
}
private function generate_url($method, $args) {
$str = '&';
foreach ($args as $key => $value) {
$str .= $key . '=' . $value . '&';
}
$url = self::ENDPOINT . '?method=' . $method . '&extended=1&&api_key=' . self::API_KEY . $str;
return $url;
}
public function get_latest_tracks($args) {
$dir = 'cached-files/';
$cachefile = $dir . date( 'mdY' ) . '.txt';
if( file_exists($cachefile) && time() - self::CACHETIME < filemtime($cachefile) ) {
$tracks = file_get_contents( $cachefile );
$tracks = json_decode( $tracks );
} else {
$tracks = file_get_contents( $this->generate_url( 'user.getrecenttracks', $args ) );
$this->create_dir( $dir );
file_put_contents( $cachefile, $tracks );
$tracks = json_decode( $tracks );
}
return $tracks->recenttracks->track;
}
public function get_latest_loved_tracks($args) {
$dir = 'cached-files/';
$cachefile = $dir . date( 'mdY' ) . '.loved.txt';
if( file_exists($cachefile) && time() - self::CACHETIME < filemtime($cachefile) ) {
$tracks = file_get_contents( $cachefile );
$tracks = json_decode( $tracks );
} else {
$tracks = file_get_contents( $this->generate_url( 'user.getLovedTracks', $args ) );
$this->create_dir( $dir );
file_put_contents( $cachefile, $tracks );
$tracks = json_decode( $tracks );
}
return $tracks->lovedtracks->track;
}
public function get_album_url($album, $artist) {
$album_uri = str_replace( ' ','+', $album );
$artist_uri = str_replace( ' ','+', $artist );
return self::URL . $artist_uri . '/' . $album_uri;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment