Mianki wrote:
You'll have to be active so the level rises up? And if you're not, the level goes down?
Nah, once you hit a level - you have it. Just like that.
More active on Last.fm you are, your level gets higher and higher.
Anyway... Code. Kohana Framework 3.0. Will work under sl33k though.
<?php defined('SYSPATH') or die('No direct script access.');
class Controller_Lastfm extends Controller_Core {
// Model for fetching and processing data
protected $model;
// Actions
public function action_index()
{
// Spawn model
$this->model = new Model_Lastfm();
// See if we have username.
// If not, output the default view.
if ($this->model->username == null)
{
$this->template->title = 'Last.fm Labs';
$this->template->content = View::factory('lastfm/main');
}
else
{
// Cookin'!
$data = $this->cook();
// Output stuff in the view
$this->template->title = 'Last.fm Labs - '.$this->model->username;
$this->template->content = View::factory('lastfm/magic')->bind('level', $data)->bind('username', $this->model->username);
}
}
// Method stubs
private function cook()
{
// Get the cooked data!
$level = $this->model->parse_and_cook();
return $level;
}
<?php defined('SYSPATH') or die('No direct script access.');
class Model_Lastfm extends Model {
// Just username, no?
public $username = null;
// API key
protected $key = 'nope.avi';
// Constructor
public function __construct()
{
if (!isset($_POST['username'])) $this->username = null;
else $this->username = Enforcer::clean_str($_POST['username']);
}
// Cookin'!
public function parse_and_cook()
{
// First, see what is the overall user playcount
$playcount = $this->api_call('user.getInfo')->user->playcount;
// Now see how much loved tracks does he have
$loved = $this->api_call('user.getLovedTracks')->lovedtracks->track; $lovedcount = count($loved);
// Now get friends
$friends = $this->api_call('user.getFriends')->friends->user; $friendcount = count($friends);
// Cook data
$level = (($playcount + $loved + $friends) / 3) / 600;
if ($level < 1) $level = 1; if ($level > 99) $level = 99;
// Return stuff!
return round($level);
}
// Last.fm API call
private function api_call($method)
{
// Try to perform an API call and throw an exception if status is not "ok".
try
{
// Get a document from cache or new one
$fp = file_get_contents('http://ws.audioscrobbler.com/2.0/?method='.$method.'&user='.$this->username.'&api_key='.$this->key);
// Parse
$xml = new SimpleXMLElement($fp);
if ($xml->lfm['status'] == "ok") throw new Exception('Last.fm API failure'); else return $xml;
}
catch (Exception $e)
{
Sleek_ExceptionControl::exception($e->getMessage());
}
}
}
Views are simple to figure out yourselves.