Empty commit

This commit is contained in:
Git 2013-01-11 08:00:38 +00:00
parent 50bf0f7f4a
commit a678bedeb4
9 changed files with 565 additions and 358 deletions

View File

@ -1,117 +1,144 @@
<?
<?
define('LASTFM_API_URL', 'http://ws.audioscrobbler.com/2.0/?method=');
class LastFM {
class LastFM
{
public static function get_artist_events($ArtistID, $Artist, $Limit = 15)
{
global $Cache;
$ArtistEvents = $Cache->get_value('artist_events_' . $ArtistID);
if (empty($ArtistEvents)) {
$ArtistEvents = self::lastfm_request("artist.getEvents", array("artist" => $Artist, "limit" => $Limit));
$Cache->cache_value('artist_events_' . $ArtistID, $ArtistEvents, 432000);
}
return $ArtistEvents;
}
public static function get_artist_events($ArtistID, $Artist, $Limit = 15) {
global $Cache;
$ArtistEvents = $Cache->get_value('artist_events_' . $ArtistID);
if (empty($ArtistEvents)) {
$ArtistEvents = self::lastfm_request("artist.getEvents", array("artist" => $Artist, "limit" => $Limit));
$Cache->cache_value('artist_events_' . $ArtistID, $ArtistEvents, 432000);
}
return $ArtistEvents;
}
public static function get_user_info($Username)
{
global $Cache;
$Response = $Cache->get_value('lastfm_user_info_' . $Username);
if (empty($Response)) {
$Response = self::lastfm_request("user.getInfo", array("user" => $Username));
$Cache->cache_value('lastfm_user_info_' . $Username, $Response, 86400);
}
return $Response;
}
public static function get_user_info($Username) {
global $Cache;
$Response = $Cache->get_value('lastfm_user_info_' . $Username);
if (empty($Response)) {
$Response = self::lastfm_request("user.getInfo", array("user" => $Username));
$Cache->cache_value('lastfm_user_info_' . $Username, $Response, 86400);
}
return $Response;
}
public static function get_recent_tracks($Username, $Limit = 15)
{
global $Cache;
$Response = $Cache->get_value('lastfm_recent_tracks_' . $Username);
if (empty($Response)) {
$Response = self::lastfm_request("user.getRecentTracks", array("user" => $Username, "limit" => $Limit));
$Cache->cache_value('lastfm_recent_tracks_' . $Username, $Response, 7200);
}
return $Response;
}
public static function compare_user_with($Username1, $Limit = 15) {
global $Cache, $LoggedUser, $DB;
$DB->query("SELECT username FROM lastfm_users WHERE ID='$LoggedUser[ID]'");
if ($DB->record_count() > 0) {
list($Username2) = $DB->next_record();
//Make sure the usernames are in the correct order to avoid dupe cache keys.
if (strcasecmp($Username1, $Username2)) {
$Temp = $Username1;
$Username1 = $Username2;
$Username2 = $Temp;
}
$Response = $Cache->get_value('lastfm_compare_' . $Username1 . '_' . $Username2);
if (empty($Response)) {
$Response = self::lastfm_request("tasteometer.compare", array("type1" => "user", "type2" => "user", "value1" => $Username1, "value2" => $Username2, "limit" => $Limit));
$Response = json_encode($Response);
$Cache->cache_value('lastfm_compare_' . $Username1 . '_' . $Username2, $Response, 86400);
}
return $Response;
}
}
public static function get_top_artists($Username, $Limit = 15)
{
global $Cache;
$Response = $Cache->get_value('lastfm_top_artists_' . $Username);
if (empty($Response)) {
$Response = self::lastfm_request("user.getTopArtists", array("user" => $Username, "limit" => $Limit));
$Cache->cache_value('lastfm_top_artists_' . $Username, $Response, 86400);
}
return $Response;
}
public static function get_last_played_track($Username) {
global $Cache;
$Response = $Cache->get_value('lastfm_last_played_track_' . $Username);
if (empty($Response)) {
$Response = self::lastfm_request("user.getRecentTracks", array("user" => $Username, "limit" => 1));
// Take the single last played track out of the response.
$Response = $Response['recenttracks']['track'];
$Response = json_encode($Response);
$Cache->cache_value('lastfm_last_played_track_' . $Username, $Response, 7200);
}
return $Response;
}
public static function get_top_albums($Username, $Limit = 15)
{
global $Cache;
$Response = $Cache->get_value('lastfm_top_albums_' . $Username);
if (empty($Response)) {
$Response = self::lastfm_request("user.getTopAlbums", array("user" => $Username, "limit" => $Limit));
$Cache->cache_value('lastfm_top_albums_' . $Username, $Response, 86400);
}
return $Response;
}
public static function get_top_artists($Username, $Limit = 15) {
global $Cache;
$Response = $Cache->get_value('lastfm_top_artists_' . $Username);
if (empty($Response)) {
sleep(1);
$Response = self::lastfm_request("user.getTopArtists", array("user" => $Username, "limit" => $Limit));
$Response = json_encode($Response);
$Cache->cache_value('lastfm_top_artists_' . $Username, $Response, 86400);
}
return $Response;
}
public static function get_top_tracks($Username, $Limit = 15)
{
global $Cache;
$Response = $Cache->get_value('lastfm_top_tracks_' . $Username);
if (empty($Response)) {
$Response = self::lastfm_request("user.getTopTracks", array("user" => $Username, "limit" => $Limit));
$Cache->cache_value('lastfm_top_tracks_' . $Username, $Response, 86400);
}
return $Response;
}
public static function get_top_albums($Username, $Limit = 15) {
global $Cache;
$Response = $Cache->get_value('lastfm_top_albums_' . $Username);
if (empty($Response)) {
sleep(2);
$Response = self::lastfm_request("user.getTopAlbums", array("user" => $Username, "limit" => $Limit));
$Response = json_encode($Response);
$Cache->cache_value('lastfm_top_albums_' . $Username, $Response, 86400);
}
return $Response;
}
public static function compare_user_with($Username1, $Limit = 15)
{
global $Cache, $LoggedUser, $DB;
$DB->query("SELECT username FROM lastfm_users WHERE ID='$LoggedUser[ID]'");
if ($DB->record_count() > 0) {
list($Username2) = $DB->next_record();
//Make sure the usernames are in the correct order to avoid dupe cache keys.
if (strcasecmp($Username1, $Username2)) {
$Temp = $Username1;
$UsernameA = $Username2;
$Username1 = $Temp;
}
$Response = $Cache->get_value('lastfm_compare_' . $Username1 . '_' . $Username2);
if (empty($Response)) {
$Response = self::lastfm_request("tasteometer.compare", array("type1" => "user", "type2" => "user", "value1" => $Username1, "value2" => $Username2, "limit" => $Limit));
$Cache->cache_value('lastfm_compare_' . $Username1 . '_' . $Username2, $Response, 86400);
}
return $Response;
}
}
public static function get_top_tracks($Username, $Limit = 15) {
global $Cache;
$Response = $Cache->get_value('lastfm_top_tracks_' . $Username);
if (empty($Response)) {
sleep(3);
$Response = self::lastfm_request("user.getTopTracks", array("user" => $Username, "limit" => $Limit));
$Response = json_encode($Response);
$Cache->cache_value('lastfm_top_tracks_' . $Username, $Response, 86400);
}
return $Response;
}
private static function lastfm_request($Method, $Args)
{
if (!defined('LASTFM_API_KEY')) {
return false;
}
$Url = LASTFM_API_URL . $Method;
if (is_array($Args)) {
foreach ($Args as $Key => $Value) {
$Url .= "&" . $Key . "=" . urlencode($Value);
}
$Url .= "&format=json&api_key=" . LASTFM_API_KEY;
public static function clear_cache($Username, $Uid) {
global $Cache, $LoggedUser, $DB;
$Response = $Cache->get_value('lastfm_clear_cache_' . $LoggedUser . '_' . $_GET['id']);
if (empty($Response)) {
// Prevent clearing the cache on the same uid page for the next 10 minutes.
$Response = $Cache->cache_value('lastfm_clear_cache_' . $LoggedUser . '_' . $Uid, $Username, 600);
$Cache->delete_value('lastfm_user_info_' . $Username);
$Cache->delete_value('lastfm_last_played_track_' . $Username);
$Cache->delete_value('lastfm_top_artists_' . $Username);
$Cache->delete_value('lastfm_top_albums_' . $Username);
$Cache->delete_value('lastfm_top_tracks_' . $Username);
$DB->query("SELECT username FROM lastfm_users WHERE ID='$LoggedUser[ID]'");
if ($DB->record_count() > 0) {
list($Username2) = $DB->next_record();
//Make sure the usernames are in the correct order to avoid dupe cache keys.
if (strcasecmp($Username, $Username2)) {
$Temp = $Username;
$Username = $Username2;
$Username2 = $Temp;
}
$Cache->delete_value('lastfm_compare_' . $Username . '_' . $Username2);
}
}
}
private static function lastfm_request($Method, $Args) {
if (!defined('LASTFM_API_KEY')) {
return false;
}
$Url = LASTFM_API_URL . $Method;
if (is_array($Args)) {
foreach ($Args as $Key => $Value) {
$Url .= "&" . $Key . "=" . urlencode($Value);
}
$Url .= "&format=json&api_key=" . LASTFM_API_KEY;
$Curl = curl_init();
curl_setopt($Curl, CURLOPT_HEADER, 0);
curl_setopt($Curl, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($Curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($Curl, CURLOPT_URL, $Url);
$Return = curl_exec($Curl);
curl_close($Curl);
return json_decode($Return, true);
}
}
$Curl = curl_init();
curl_setopt($Curl, CURLOPT_HEADER, 0);
curl_setopt($Curl, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($Curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($Curl, CURLOPT_URL, $Url);
$Return = curl_exec($Curl);
curl_close($Curl);
return json_decode($Return, true);
}
}
}

View File

@ -419,7 +419,7 @@ public static function gen_crypt_salt() {
* @return HTML formatted username
*/
public static function format_username($UserID, $Badges = false, $IsWarned = true, $IsEnabled = true, $Class = false, $Title = false) {
global $Classes;
global $Classes, $LoggedUser;
// This array is a hack that should be made less retarded, but whatevs
// PermID => ShortForm
@ -445,8 +445,12 @@ public static function format_username($UserID, $Badges = false, $IsWarned = tru
if ($Badges) {
$Str .= ($UserInfo['Donor'] == 1) ? '<a href="donate.php"><img src="'.STATIC_SERVER.'common/symbols/donor.png" alt="Donor" title="Donor" /></a>' : '';
}
$Str .= ($IsWarned && $UserInfo['Warned'] != '0000-00-00 00:00:00') ? '<a href="wiki.php?action=article&amp;id=218"><img src="'.STATIC_SERVER.'common/symbols/warned.png" alt="Warned" title="Warned" /></a>' : '';
}
$Str .= ($IsWarned && $UserInfo['Warned'] != '0000-00-00 00:00:00') ? '<a href="wiki.php?action=article&amp;id=218"'
. '><img src="'.STATIC_SERVER.'common/symbols/warned.png" alt="Warned" title="Warned'
. ($LoggedUser['ID'] === $UserID ? ' - Expires ' . date('Y-m-d h:i', strtotime($UserInfo['Warned'])) : '')
. '" /></a>' : '';
$Str .= ($IsEnabled && $UserInfo['Enabled'] == 2) ? '<a href="rules.php"><img src="'.STATIC_SERVER.'common/symbols/disabled.png" alt="Banned" title="Be good, and you won\'t end up like this user" /></a>' : '';
if ($Badges) {

View File

@ -67,7 +67,7 @@
<td>
<input type="text" name="comment" value="<?=display_str($Result['Comment'])?>" size="60"/>
</td>
<td><?=Users::format_username($Result['$UserID'], false, false, false)
<td><?=Users::format_username($Result['UserID'], false, false, false)
?><br/><?=time_diff($Result['Time'], 1)
?></td>
<td>
@ -78,4 +78,8 @@
</tr>
<? }?>
</table>
<div class="linkbox pager">
<br />
<?=$Pages?>
</div>
<? View::show_footer(); ?>

View File

@ -243,34 +243,35 @@ function checked($Checked) {
</select>
</td>
</tr>
<tr>
<td class="label"><strong>Push Notifications</strong></td>
<td>
<select name="pushservice" id="pushservice">
<option value="0" <? if(empty($PushService)) { ?> selected="selected" <? } ?>/>Disable Push Notifications</option>
<option value="1" <? if($PushService == 1) { ?> selected="selected" <? } ?>/>Notify My Android</option>
<option value="2" <? if($PushService == 2) { ?> selected="selected" <? } ?>/>Prowl</option>
<option value="3" <? if($PushService == 3) { ?> selected="selected" <? } ?>/>Notifo</option>
<option value="4" <? if($PushService == 4) { ?> selected="selected" <? } ?>/>Super Toasty</option>
</select>
<div id="pushsettings" style="display: none">
<br />
<label id="pushservice_title" for="pushkey">API Key</label>
<input type="text" size="50" name="pushkey" id="pushkey" value="<?=display_str($PushOptions['PushKey'])?>" />
<div id="pushsettings_username" style="display: none">
<label for="pushusername">Username</label> <input type="text"
size="50" name="pushusername" id="pushusername"
value="<?=display_str($PushOptions['PushUsername'])?>" />
</div>
<br />
Push me on
<br />
<input type="checkbox" name="pushfilters[]" value="News" <? if(isset($PushOptions['PushFilters']['News'])) { ?> checked="checked" <? } ?>/>Announcements<br />
<input type="checkbox" name="pushfilters[]" value="PM" <? if(isset($PushOptions['PushFilters']['PM'])) { ?> checked="checked" <? } ?>/>Private Messages<br />
<input type="checkbox" name="pushfilters[]" value="Quote" <? if(isset($PushOptions['PushFilters']['Quote'])) { ?> checked="checked" <? } ?>/>Quote Notifications<br />
<!--
?>
<!-- -->
<tr>
<td class="label"><strong>Auto-save Text</strong></td>
<td>
<input type="checkbox" name="disableautosave" id="disableautosave" <? if (!empty($SiteOptions['DisableAutoSave'])) { ?>checked="checked"<? } ?> />
<label for="disableautosave">Disable reply text from being saved automatically when changing pages in a thread</label>
</td>
</tr>
<tr>
<td class="label"><strong>Voting links</strong></td>
<td>
<input type="checkbox" name="novotelinks" id="novotelinks" <? if (!empty($SiteOptions['NoVoteLinks'])) { ?>checked="checked"<? } ?> />
<label for="novotelinks">Disable voting links on artist pages, collages, and snatched lists</label>
</td>
</tr>
<tr>
<td class="label"><strong>Download torrents as text files</strong></td>
<td>
<input type="checkbox" name="downloadalt" id="downloadalt" <? if ($DownloadAlt) { ?>checked="checked"<? } ?> />
<label for="downloadalt">For users whose ISP block the downloading of torrent files</label>
</td>
</tr>
<tr>
<td class="label"><strong>Unseeded torrent alerts</strong></td>
<td>
<input type="checkbox" name="unseededalerts" id="unseededalerts" <?=checked($UnseededAlerts)?> />
<label for="unseededalerts">Receive a PM alert before your uploads are deleted for being unseeded</label>
</td>
</tr>
<tr class="colhead_dark">
<td colspan="2">
<strong>User info</strong>

View File

@ -92,6 +92,37 @@
include(SERVER_ROOT.'/sections/user/user.php');
break;
//Provide public methods for Last.fm data gets.
case 'lastfm_compare':
if(isset($_GET['username'])) {
echo LastFM::compare_user_with($_GET['username']);
}
break;
case 'lastfm_last_played_track':
if(isset($_GET['username'])) {
echo LastFM::get_last_played_track($_GET['username']);
}
break;
case 'lastfm_top_artists':
if(isset($_GET['username'])) {
echo LastFM::get_top_artists($_GET['username']);
}
break;
case 'lastfm_top_albums':
if(isset($_GET['username'])) {
echo LastFM::get_top_albums($_GET['username']);
}
break;
case 'lastfm_top_tracks':
if(isset($_GET['username'])) {
echo LastFM::get_top_tracks($_GET['username']);
}
break;
case 'lastfm_clear_cache':
if(isset($_GET['username']) && isset($_GET['uid'])) {
echo LastFM::clear_cache($_GET['username'],$_GET['uid']);
}
break;
default:
if (isset($_REQUEST['id'])) {
include(SERVER_ROOT.'/sections/user/user.php');

View File

@ -1,58 +1,32 @@
<?
//Include Last.fm in the user sidebar only if a Last.fm username is specified.
$DB->query("SELECT username FROM lastfm_users WHERE ID = '$UserID'");
if ($DB->record_count()) {
list($LastFMUsername) = $DB->next_record();
$LastFMInfo = LastFM::get_user_info($LastFMUsername);
$RecentTracks = LastFM::get_recent_tracks($LastFMUsername);
?>
<div class="box">
<div class="head">
<span style="float:left;">Last.FM
<span id="tabs" class="tabs">
<a href="#" style="font-weight: bold;">[Info]</a>
<a href="#">[Top Artists]</a>
<a href="#">[Top Albums]</a>
<a href="#">[Top Tracks]</a>
<a href="#">[Tasteometer]</a>
</span>
</span>
<span style="float:right;"><a href="#" onclick="$('#lastfm_div').toggle(); this.innerHTML=(this.innerHTML=='(Hide)'?'(Show)':'(Hide)'); return false;">(Hide)</a></span>&nbsp;
list($LastFMUsername) = $DB->next_record();
$LastFMInfo = LastFM::get_user_info($LastFMUsername);
//Hand everything else over to js (gets data via the username in an id-d div) to allow faster page loading.
?>
<div class="box box_info box_lastfm">
<div class="head colhead_dark">Last.fm</div>
<ul class="stats nobullet">
<li>
Username: <a id="lastfm_username" href="<?= $LastFMInfo['user']['url'] ?>" title="<?= $LastFMInfo['user']['name'] ?> on Last.fm: <?= $LastFMInfo['user']['playcount'] ?> plays, <?= $LastFMInfo['user']['playlists'] ?> playlists."><?= $LastFMInfo['user']['name'] ?></a>
</li>
<div id="lastfm_stats">
</div>
<li id="lastfm_loading">
Loading...
</li>
<?
//Append the reload stats button only if allowed on the current user page.
$Response = $Cache->get_value('lastfm_clear_cache_' . $LoggedUser . '_' . $_GET['id']);
if (empty($Response)) :
?>
<li id="lastfm_reload_container">
[<a href="#" id="lastfm_reload" onclick="return false">Reload stats</a>]
</li>
<? endif; ?>
</ul>
</div>
<div class="pad" id="lastfm_div">
<div id="contents_div">
<div id="tab_0_contents">
<div class="lastfm_user_info">
<strong><a id="lastfm_username" href="<?=$LastFMInfo['user']['url']?>"><?=$LastFMInfo['user']['name']?></a></strong>
<br/>Number of plays: <?=$LastFMInfo['user']['playcount']?>
<br/>Playlists: <?=$LastFMInfo['user']['playlists']?>
</div>
<br/>
<div class="lastfm_recent_tracks">
<strong>Recently Played</strong>
<ul class="nobullet">
<?
foreach ($RecentTracks['recenttracks']['track'] as $Track) {
?>
<li>
<a href="torrents.php?searchstr=<?=$Track['artist']['#text']?>"><?=$Track['artist']['#text']?></a> - <a href="<?=$Track['url']?>"><?=$Track['name']?></a> - <a href="torrents.php?searchstr=<?=$Track['album']['#text']?>"><?=$Track['album']['#text']?></a>
</li>
<?
}
?>
</ul>
</div>
</div>
<div id="tab_1_contents">
</div>
<div id="tab_2_contents">
</div>
<div id="tab_3_contents">
</div>
<div id="tab_4_contents">
</div>
</div>
</div>
</div>
<? } ?>

View File

@ -151,9 +151,7 @@ function check_paranoia_here($Setting) {
$Badges.=($Warned!='0000-00-00 00:00:00') ? '<img src="'.STATIC_SERVER.'common/symbols/warned.png" alt="Warned" />' : '';
$Badges.=($Enabled == '1' || $Enabled == '0' || !$Enabled) ? '': '<img src="'.STATIC_SERVER.'common/symbols/disabled.png" alt="Banned" />';
View::show_header($Username,'user,bbcode,requests');
View::show_header($Username,'user,bbcode,requests,jquery,lastfm');
?>
<div class="thin">
@ -242,10 +240,17 @@ function check_paranoia_here($Setting) {
<? } ?>
<? if ($OwnProfile || ($Override=check_paranoia_here(false)) || check_perms('users_mod')) { ?>
<li <?= $Override===2 ? 'class="paranoia_override"' : ''?>><a href="userhistory.php?action=token_history&amp;userid=<?=$UserID?>">Tokens</a>: <?=number_format($FLTokens)?></li>
<? }
if (($OwnProfile || check_perms('users_mod')) && $Warned!='0000-00-00 00:00:00') { ?>
<li <?= $Override===2 ? 'class="paranoia_override"' : ''?>>Warning expires: <?= date('Y-m-d h:i', strtotime($Warned)) ?></li>
<? } ?>
</ul>
</div>
<?
//Last.fm statistics and comparability
include(SERVER_ROOT.'/sections/user/lastfm.php');
if (check_paranoia_here('requestsfilled_count') || check_paranoia_here('requestsfilled_bounty')) {
$DB->query("SELECT COUNT(DISTINCT r.ID), SUM(rv.Bounty) FROM requests AS r LEFT JOIN requests_votes AS rv ON r.ID=rv.RequestID WHERE r.FillerID = ".$UserID);
@ -627,7 +632,6 @@ function check_paranoia_here($Setting) {
$FirstCol = false;
}
include(SERVER_ROOT.'/sections/user/lastfm.php');

View File

@ -1,171 +1,324 @@
(function ($) {
var TAB_COUNT = 0;
var topArtistsLoaded = false;
var topAlbumsLoaded = false;
var topTracksLoaded = false;
var tasteometerLoaded = false;
var username;
$(document).ready(function () {
init();
});
var username;
// How many entries to show per category before expanding
var initialCount = 3;
var tasteometer = "";
var lastPlayedTrack = "";
var sharedArtists = "";
var topArtists = "";
var topAlbums = "";
var topTracks = "";
// Failed request flag.
var flag = 0;
$(document).ready(function () {
// Avoid conflicting with other jQuery instances (userscripts et al).
$.noConflict();
// Fetch the username (appended from php) to base all get requests on.
username = $('#lastfm_username').text();
var div = $('#lastfm_stats');
// Fetch the required data.
// If data isn't cached, delays are issued in the class to avoid too many parallel requests to Last.fm
getTasteometer(div);
getLastPlayedTrack(div);
getTopArtists(div);
getTopAlbums(div);
getTopTracks(div);
// Allow expanding the show information to more than three entries.
// Attach to document as lastfm_expand links are added dynamically when fetching the data.
$(document).on('click', "#lastfm_expand", function () {
// Make hidden entries visible and remove the expand button.
if ( $(this).attr("href") == "#sharedartists" ){
sharedArtists = sharedArtists.replace(/\ class="hidden"/g,"");
sharedArtists = sharedArtists.replace(/<li>\[<a\ href=\"#sharedartists.*\]<\/li>/,"");
} else if ( $(this).attr("href") == "#topartists" ){
topArtists = topArtists.replace(/\ class="hidden"/g,"");
topArtists = topArtists.replace(/<li>\[<a\ href=\"#topartists.*\]<\/li>/,"");
} else if ( $(this).attr("href") == "#topalbums" ){
topAlbums = topAlbums.replace(/\ class="hidden"/g,"");
topAlbums = topAlbums.replace(/<li>\[<a\ href=\"#topalbums.*\]<\/li>/,"");
} else if ( $(this).attr("href") == "#toptracks" ){
topTracks = topTracks.replace(/\ class="hidden"/g,"");
topTracks = topTracks.replace(/<li>\[<a\ href=\"#toptracks.*\]<\/li>/,"");
}
updateDivContents(div);
});
// Allow reloading the data manually.
$.urlParam = function(name){
var results = new RegExp('[\\?&amp;]' + name + '=([^&amp;#]*)').exec(window.location.href);
return results[1] || 0;
}
$("#lastfm_reload").on('click', function () {
// Clear the cache and the necessary variables.
$.get('user.php?action=lastfm_clear_cache&username=' + username + '&uid=' + $.urlParam('id'), function (response) {
});
tasteometer = "";
lastPlayedTrack = "";
sharedArtists = "";
topArtists = "";
topAlbums = "";
topTracks = "";
// Revert the sidebar box to its initial state.
$("#lastfm_stats").html("");
$(".box_lastfm").children("ul").append('<li id="lastfm_loading">Loading...</li>');
// Remove the stats reload button.
$("#lastfm_reload_container").remove();
getTasteometer(div);
getLastPlayedTrack(div);
getTopArtists(div);
getTopAlbums(div);
getTopTracks(div);
});
});
// Allow updating the sidebar element contents as get requests are completed.
function updateDivContents(div) {
var html = "";
// Pass all data vars, gets that haven't completed yet append empty strings.
html += tasteometer;
html += lastPlayedTrack;
html += sharedArtists;
html += topArtists;
html += topAlbums;
html += topTracks;
div.html(html);
// Once all requests are completed, remove the loading message.
if(tasteometer && lastPlayedTrack && sharedArtists && topArtists && topAlbums && topTracks){
$('#lastfm_loading').remove();
}
}
// Escape ampersands with html code to avoid breaking the search links
function escapeAmp(input){
return input.replace(/&/g,"%26");
}
function init() {
username = $('#lastfm_username').text();
$('#tabs').children('a').each(function () {
var i = TAB_COUNT;
$(this).click(function () {
switchTo(i);
return false;
});
TAB_COUNT++;
});
}
// Functions for fetching the required data are as follows.
// Also gets the data for shared artists as they're bundled.
function getTasteometer(div) {
$.get('user.php?action=lastfm_compare&username=' + username, function (response) {
// Two separate elements are received from one Last.fm API call.
var tasteometerHtml = "";
var sharedArtistsHtml = "";
if ( response ){
json = JSON.parse(response);
if (json != null && json['error']) {
console.log("Tasteometer: " + json['message']);
// Specified non-existant username for Last.fm, remove Last.fm box from page.
if (json['error'] == "7" ){
tasteometer = " ";
sharedArtists = " ";
}
} else if (json == null) {
// No Last.fm compare possible.
tasteometer = " ";
sharedArtists = " ";
} else {
var j = json['comparison']['result'];
var a = j['artists']['artist'];
tasteometerHtml += "<li>Compatibility: ";
var compatibility = Math.round(j['score'] * 100);
var background;
if (compatibility < 50){
background = 'rgb(255, '+Math.floor(255*compatibility/50)+', 0)'
} else {
background = 'rgb('+Math.floor((1-(compatibility-50)/50)*255)+', 255, 0)'
}
tasteometerHtml += compatibility + '%\r\
<li>\r\
<div id="lastfm_compatibilitybar_container">\n\
<div id="lastfm_compatibilitybar" style="width: '+compatibility+'%; background: '+background+';">\n\
</div>\r\
</div>\r\
</li>';
// Only print shared artists if there are any
if (j['artists']['matches'] != 0){
sharedArtistsHtml += '<li>Shared artists:</li><li><ul class="nobullet">';
var k = initialCount;
if (a.length < 3) k = a.length;
for (var i = 0; i < k; i++) {
sharedArtistsHtml += '<li><a href="artist.php?artistname=' + escapeAmp(a[i]['name']) + '">' + a[i]['name'] + '</a></li>'
}
if ( a.length > 3 ){
for (i = 3; i < a.length; i++) {
sharedArtistsHtml += '<li class="hidden"><a href="artist.php?artistname=' + escapeAmp(a[i]['name']) + '">' + a[i]['name'] + '</a></li>'
}
sharedArtistsHtml += '<li>[<a href="#sharedartists" id="lastfm_expand" onclick="return false">Expand</a>]</li>'
}
sharedArtistsHtml += '</ul></li>';
sharedArtists = sharedArtistsHtml;
} else {
// Allow removing loading message regardless.
sharedArtists = " ";
}
tasteometerHtml += "</li>";
tasteometer = tasteometerHtml;
}
} else {
sharedArtists = " ";
tasteometer = " ";
}
updateDivContents(div);
});
}
function getLastPlayedTrack(div) {
$.get('user.php?action=lastfm_last_played_track&username=' + username, function (response) {
var html = "";
if ( response ){
var json = JSON.parse(response);
if (json != null && json['error']) {
console.log("Last played track: " + json['message']);
lastPlayedTrack = " ";
}
else if (json == null) {
// No last played track available.
// Allow removing the loading message regardless.
lastPlayedTrack = " ";
}
else {
// Fix Last.fm API returning more than one entry despite limit on certain conditions.
if ( typeof(json[0]) === "object" ) json = json[0];
html += "<li>Last played: ";
html += '<a href="artist.php?artistname=' + escapeAmp(json['artist']['#text']) + '">' + json['artist']['#text'] + '</a> - <a href="torrents.php?searchstr=' + escapeAmp(json['name']) + '">' + json['name'] + '</a>';
html += "</li>";
lastPlayedTrack = html;
}
} else {
lastPlayedTrack = " ";
}
updateDivContents(div);
});
}
function getTopArtists(div) {
$.get('user.php?action=lastfm_top_artists&username=' + username, function (response) {
var html;
if ( response ){
var json = JSON.parse(response);
if (json != null && json['error']) {
console.log("Top artists: " + json['message']);
topArtists = " ";
}
else if (json == null) {
console.log("Error: json == null");
topArtists = " ";
} else if ( json['topartists']['total']==0 ) {
// No top artists for the specified user, possibly a new Last.fm account.
// Allow removing the loading message regardless.
topArtists = " ";
} else {
html = "<li>Top Artists:</li>";
html += "<li>";
var j = json['topartists']['artist'];
html += '<ul class="nobullet">';
var k = initialCount;
if (j.length < 3) k = j.length;
for (var i = 0; i < k; i++) {
html += '<li><a href="artist.php?artistname=' + escapeAmp(j[i]['name']) + '">' + j[i]['name'] + '</a></li>'
}
if ( j.length>3 ){
for (i = 3; i < j.length; i++) {
html += '<li class="hidden"><a href="artist.php?artistname=' + escapeAmp(j[i]['name']) + '">' + j[i]['name'] + '</a></li>'
}
html+= '<li>[<a href="#topartists" id="lastfm_expand" onclick="return false">Expand</a>]</li>'
}
html += '</ul>';
html += "</li>";
topArtists = html;
}
} else {
topArtists = " ";
}
updateDivContents(div);
});
}
function getTopArtists(div) {
if (!topArtistsLoaded) {
div.html('Loading...');
ajax.get('user.php?action=lastfm_top_artists&username=' + username, function (response) {
var json = JSON.parse(response);
if (json != null && json['error']) {
div.html(json['message']);
}
else if (json == null) {
div.html("Error");
}
else {
var j = json['topartists']['artist'];
var html = '<strong>Top Artists</strong><ul class="nobullet">';
for (var i = 0; i < j.length; i++) {
html += '<li><a href="torrents.php?searchstr=' + j[i]['name'] + '">' + j[i]['name'] + '</a></li>'
}
html += '</ul>';
div.html(html);
topArtistsLoaded = true;
}
});
}
}
function getTopAlbums(div) {
if (!topAlbumsLoaded) {
div.html('Loading...');
ajax.get('user.php?action=lastfm_top_albums&username=' + username, function (response) {
var json = JSON.parse(response);
if (json != null && json['error']) {
div.html(json['message']);
}
else if (json == null) {
div.html("Error");
}
else {
var j = json['topalbums']['album'];
var html = '<strong>Top Albums</strong><ul class="nobullet">';
for (var i = 0; i < j.length; i++) {
html += '<li><a href="torrents.php?searchstr=' + j[i]['name'] + '">' + j[i]['name'] + '</a> - <a href="torrents.php?searchstr=' + j[i]['artist']['name'] + '">' + j[i]['artist']['name'] + '</a></li>'
}
html += '</ul>';
div.html(html);
topAlbumsLoaded = true;
}
});
}
}
function getTopTracks(div) {
if (!topTracksLoaded) {
div.html('Loading...');
if (json != null && json['error']) {
div.html(json['message']);
}
else if (json == null) {
div.html("Error");
}
else {
ajax.get('user.php?action=lastfm_top_tracks&username=' + username, function (response) {
var json = JSON.parse(response);
var j = json['toptracks']['track'];
if (j != null) {
var html = '<strong>Top Tracks</strong><ul class="nobullet">';
for (var i = 0; i < j.length; i++) {
html += '<li><a href="torrents.php?searchstr=' + j[i]['name'] + '">' + j[i]['name'] + '</a> - <a href="torrents.php?searchstr=' + j[i]['artist']['name'] + '">' + j[i]['artist']['name'] + '</a></li>'
}
html += '</ul>';
div.html(html);
}
else {
div.html('Error');
}
topTracksLoaded = true;
});
}
}
}
function getTasteometer(div) {
if (!tasteometerLoaded) {
div.html('Loading...');
ajax.get('user.php?action=lastfm_compare_users&username=' + username, function (response) {
var json = JSON.parse(response);
if (json != null && json['error']) {
div.html(json['message']);
}
else if (json == null) {
div.html("Error, do you have your Last.FM username set in settings?");
}
else {
var j = json['comparison']['result'];
var a = j['artists']['artist'];
console.log(a);
var compatibility = Math.round(j['score'] * 100);
var html = '<strong>Tasteometer</strong><br/>Compatibility: ' + compatibility + '% <ul class="nobullet">';
for (var i = 0; i < a.length; i++) {
html += '<li><a href="torrents.php?searchstr=' + a[i]['name'] + '">' + a[i]['name'] + '</li>'
}
html += '</ul>';
div.html(html);
tasteometerLoaded = true;
}
});
}
}
function switchTo(tab) {
var i = 0;
$('#tabs').children('a').each(function () {
if (i != tab) {
$(this).css('font-weight', '');
} else {
$(this).css('font-weight', 'bold');
}
i++;
});
i = 0;
$('#contents_div').children('div').each(function () {
if (i != tab) {
$(this).hide();
} else {
$(this).show();
switch (tab) {
case 1:
getTopArtists($(this));
break;
case 2:
getTopAlbums($(this));
break;
case 3:
getTopTracks($(this));
break;
case 4:
getTasteometer($(this));
break;
default:
break;
}
}
i++;
});
}
function getTopAlbums(div) {
$.get('user.php?action=lastfm_top_albums&username=' + username, function (response) {
var html;
if ( response ){
var json = JSON.parse(response);
if (json != null && json['error']) {
console.log("Top albums: " + json['message']);
topAlbums = " ";
}
else if (json == null) {
console.log("Error: json == null");
topAlbums = " ";
} else if ( json['topalbums']['total']==0 ) {
// No top artists for the specified user, possibly a new Last.fm account.
// Allow removing the loading message regardless.
topAlbums = " ";
} else {
var j = json['topalbums']['album'];
html = "<li>Top Albums:</li>";
html += "<li>";
html += '<ul class="nobullet">';
var k = initialCount;
if (j.length < 3) k = j.length;
for (var i = 0; i < k; i++) {
html += '<li><a href="artist.php?artistname=' + escapeAmp(j[i]['artist']['name']) + '">' + j[i]['artist']['name'] + '</a> - <a href="torrents.php?searchstr=' + escapeAmp(j[i]['name']) + '">' + j[i]['name'] + '</a></li>'
}
if ( j.length>3 ){
for (i = 3; i < j.length; i++) {
html += '<li class="hidden"><a href="artist.php?artistname=' + escapeAmp(j[i]['artist']['name']) + '">' + j[i]['artist']['name'] + '</a> - <a href="torrents.php?searchstr=' + escapeAmp(j[i]['name']) + '">' + j[i]['name'] + '</a></li>'
}
html+= '<li>[<a href="#topalbums" id="lastfm_expand" onclick="return false">Expand</a>]</li>'
}
html += '</ul>';
html += "</li>";
topAlbums = html;
}
} else {
topAlbums = " ";
}
updateDivContents(div);
});
}
function getTopTracks(div) {
$.get('user.php?action=lastfm_top_tracks&username=' + username, function (response) {
var html;
if ( response ){
var json = JSON.parse(response);
if (json != null && json['error']) {
console.log("Toptracks: " + json['message']);
topTracks = " ";
}
else if (json == null) {
console.log("Error: json == null");
topTracks = " ";
} else if ( json['toptracks']['total']==0 ) {
// No top artists for the specified user, possibly a new Last.fm account.
// Allow removing the loading message regardless.
topTracks = " ";
} else {
html = "<li>Top Tracks:</li>";
html += "<li>";
var j = json['toptracks']['track'];
html += '<ul class="nobullet">';
var k = initialCount;
if (j.length < 3) k = j.length;
for (var i = 0; i < k; i++) {
html += '<li><a href="artist.php?artistname=' + escapeAmp(j[i]['artist']['name']) + '">' + j[i]['artist']['name'] + '</a> - <a href="torrents.php?searchstr=' + escapeAmp(j[i]['name']) + '">' + j[i]['name'] + '</a></li>'
}
if ( j.length>3 ){
for (i = 3; i < j.length; i++) {
html += '<li class="hidden"><a href="artist.php?artistname=' + escapeAmp(j[i]['artist']['name']) + '">' + j[i]['artist']['name'] + '</a> - <a href="torrents.php?searchstr=' + escapeAmp(j[i]['name']) + '">' + j[i]['name'] + '</a></li>'
}
html+= '<li>[<a href="#toptracks" id="lastfm_expand" onclick="return false">Expand</a>]</li>'
}
html += '</ul>';
html += "</li>";
topTracks = html;
}
} else {
topTracks = " ";
}
updateDivContents(div);
});
}
})(jQuery);

View File

@ -359,3 +359,12 @@ tr.torrent .bookmark>a:after {
.text_preview { min-height: 100px }
#lastfm_compatibilitybar_container {
width: 100%;
height: 5px;
background: #969696
}
#lastfm_compatibilitybar {
height: 100%;
}