Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import com.earth2me.essentials.adventure.ComponentHolder;
import com.earth2me.essentials.adventure.PaperAdventureFacet;
import com.earth2me.essentials.adventure.SpigotAdventureFacet;
import com.earth2me.essentials.commands.Commandofflineplayers;
import com.earth2me.essentials.commands.EssentialsCommand;
import com.earth2me.essentials.commands.IEssentialsCommand;
import com.earth2me.essentials.commands.NoChargeException;
Expand Down Expand Up @@ -601,6 +602,7 @@ public void onDisable() {

@Override
public void reload() {
invalidateOfflinePlayersCache();
Trade.closeLog();

for (final IConf iConf : confList) {
Expand Down Expand Up @@ -650,6 +652,13 @@ private IEssentialsCommand loadCommand(final String path, final String name, fin
return cmd;
}

public void invalidateOfflinePlayersCache() {
final IEssentialsCommand command = commandMap.get("offlineplayers");
if (command instanceof Commandofflineplayers) {
((Commandofflineplayers) command).invalidateCache();
}
}

public Map<String, IEssentialsCommand> getCommandMap() {
return commandMap;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,7 @@ public void onPlayerQuit(final PlayerQuitEvent event) {
user.setLastLogout(System.currentTimeMillis());
}
user.stopTransaction();
((Essentials) ess).invalidateOfflinePlayersCache();

user.dispose();
}
Expand Down Expand Up @@ -352,6 +353,7 @@ public void onPlayerConfigure(final AsyncPlayerConnectionConfigureEvent event) {

@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerJoin(final PlayerJoinEvent event) {
((Essentials) ess).invalidateOfflinePlayersCache();
final User user = ess.getUser(event.getPlayer());
if (user == null) {
legacyJoinFlow(event);
Expand Down Expand Up @@ -383,6 +385,7 @@ public void onPlayerJoin(final PlayerJoinEvent event) {
private final class JoinListenerPre1_21 implements Listener {
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerJoin(final PlayerJoinEvent event) {
((Essentials) ess).invalidateOfflinePlayersCache();
legacyJoinFlow(event);
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,289 @@
package com.earth2me.essentials.commands;

import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.User;
import com.earth2me.essentials.userstorage.IUserMap;
import com.earth2me.essentials.utils.DateUtil;
import org.bukkit.Server;
import org.bukkit.entity.Player;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

public class Commandofflineplayers extends EssentialsCommand {
static final int PAGE_SIZE = 10;
static final long CACHE_DURATION = TimeUnit.SECONDS.toNanos(30);

private final PlayerCache cache = new PlayerCache();

public void invalidateCache() {
cache.invalidate();
}

private final AtomicBoolean loading = new AtomicBoolean(false);

public Commandofflineplayers() {
super("offlineplayers");
}

@Override
public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) {
final int page = parsePage(args);

if (page < 1) {
sender.sendTl("offlinePlayersInvalidPage");
return;
}

final CachedPlayers currentCache = cache.getFresh(System.nanoTime());

if (currentCache != null) {
showCachedPage(server, sender, currentCache.players, page);
return;
}

if (!loading.compareAndSet(false, true)) {
sender.sendTl("offlinePlayersBusy");
return;
}

try {
final long generation = cache.getGeneration();
final Set<UUID> onlinePlayers = getOnlinePlayerUUIDs(server);
sender.sendTl("offlinePlayersLoading");

ess.runTaskAsynchronously(() -> {
try {
final List<OfflinePlayerEntry> players =
collectOfflinePlayers(ess.getUsers(), onlinePlayers);

ess.scheduleSyncDelayedTask(() -> {
try {
final CachedPlayers refreshed =
new CachedPlayers(players, System.nanoTime());

if (!cache.publish(generation, refreshed)) {
if (canReceiveResults(sender)) {
sender.sendTl("offlinePlayersChanged");
}
return;
}

showCachedPage(server, sender, refreshed.players, page);
} finally {
loading.set(false);
}
});
} catch (final Exception exception) {
loading.set(false);
ess.scheduleSyncDelayedTask(() -> {
if (canReceiveResults(sender)) {
showError(sender.getSender(), exception, commandLabel);
}
});
}
});
} catch (final RuntimeException exception) {
loading.set(false);
throw exception;
}
}

private boolean canReceiveResults(final CommandSource sender) {
return (!sender.isPlayer() || sender.getPlayer().isOnline())
&& sender.isAuthorized("essentials.offlineplayers");
}

private void showCachedPage(final Server server, final CommandSource sender,
final List<OfflinePlayerEntry> players, final int page) {
if (canReceiveResults(sender)) {
showPage(sender, filterOnlinePlayers(
players, getOnlinePlayerUUIDs(server)), page);
}
}

static List<OfflinePlayerEntry> filterOnlinePlayers(
final List<OfflinePlayerEntry> players, final Set<UUID> onlinePlayers) {
final List<OfflinePlayerEntry> result = new ArrayList<>(players);
result.removeIf(player -> onlinePlayers.contains(player.uuid));
return result;
}

static boolean hasKnownLastSeen(final long lastLogout, final long now) {
return lastLogout > 0 && lastLogout <= now;
}

static int parsePage(final String[] args) {
if (args.length == 0) {
return 1;
}

if (args.length != 1) {
return -1;
}

try {
final int page = Integer.parseInt(args[0]);
return page > 0 ? page : -1;
} catch (final NumberFormatException exception) {
return -1;
}
}

private Set<UUID> getOnlinePlayerUUIDs(final Server server) {
final Set<UUID> players = new HashSet<>();

for (final Player player : server.getOnlinePlayers()) {
players.add(player.getUniqueId());
}

return players;
}

static List<OfflinePlayerEntry> collectOfflinePlayers(
final IUserMap users, final Set<UUID> onlinePlayers) {
final List<OfflinePlayerEntry> players = new ArrayList<>();
final Set<UUID> storedPlayers = new HashSet<>(users.getAllUserUUIDs());

for (final UUID uuid : storedPlayers) {
if (onlinePlayers.contains(uuid)) {
continue;
}

final User user = users.loadUncachedUser(uuid);

if (user == null || user.isNPC()) {
continue;
}

final String name = user.getLastAccountName();

if (name == null || name.trim().isEmpty()) {
continue;
}

players.add(new OfflinePlayerEntry(uuid, name, user.getLastLogout()));
}

players.sort(Comparator
.comparing((OfflinePlayerEntry entry) -> entry.name,
String.CASE_INSENSITIVE_ORDER)
.thenComparing(entry -> entry.uuid));

return players;
}

static int getPageCount(final int total) {
return total == 0 ? 0 : (total - 1) / PAGE_SIZE + 1;
}

static List<OfflinePlayerEntry> getPage(
final List<OfflinePlayerEntry> players, final int page) {
if (page < 1 || page > getPageCount(players.size())) {
return Collections.emptyList();
}

final int start = (page - 1) * PAGE_SIZE;
final int end = start + Math.min(PAGE_SIZE, players.size() - start);

return players.subList(start, end);
}

private void showPage(final CommandSource sender,
final List<OfflinePlayerEntry> players,
final int page) {
if (players.isEmpty()) {
sender.sendTl("offlinePlayersEmpty");
return;
}

final int totalPages = getPageCount(players.size());

if (page > totalPages) {
sender.sendTl("offlinePlayersPageOutOfRange", totalPages);
return;
}

sender.sendTl("offlinePlayersHeader",
page, totalPages, players.size());

for (final OfflinePlayerEntry player : getPage(players, page)) {
if (hasKnownLastSeen(player.lastLogout, System.currentTimeMillis())) {
sender.sendTl("offlinePlayersEntry", player.name, player.uuid.toString(),
DateUtil.formatDateDiff(player.lastLogout));
} else {
sender.sendTl("offlinePlayersEntryUnknown", player.name, player.uuid.toString());
}
}
}

@Override
protected List<String> getTabCompleteOptions(
final Server server, final CommandSource sender,
final String commandLabel, final String[] args) {
return Collections.emptyList();
}

static final class OfflinePlayerEntry {
final UUID uuid;
final String name;

final long lastLogout;

OfflinePlayerEntry(final UUID uuid, final String name, final long lastLogout) {
this.uuid = uuid;
this.name = name;
this.lastLogout = lastLogout;
}
}

static final class PlayerCache {
private long generation;
private CachedPlayers current;

synchronized long getGeneration() {
return generation;
}

synchronized void invalidate() {
generation++;
current = null;
}

synchronized CachedPlayers getFresh(final long now) {
return current != null && current.isFresh(now) ? current : null;
}

synchronized boolean publish(final long expectedGeneration,
final CachedPlayers players) {
if (generation != expectedGeneration) {
return false;
}

current = players;
return true;
}
}

static final class CachedPlayers {
final List<OfflinePlayerEntry> players;
private final long createdAt;

CachedPlayers(final List<OfflinePlayerEntry> players, final long createdAt) {
this.players = Collections.unmodifiableList(new ArrayList<>(players));
this.createdAt = createdAt;
}

boolean isFresh(final long now) {
final long age = now - createdAt;
return age >= 0 && age < CACHE_DURATION;
}
}
}
13 changes: 13 additions & 0 deletions Essentials/src/main/resources/messages.properties
Original file line number Diff line number Diff line change
Expand Up @@ -904,6 +904,19 @@ nukeCommandDescription=May death rain upon them.
nukeCommandUsage=/<command> [player]
nukeCommandUsage1=/<command> [players...]
nukeCommandUsage1Description=Sends a nuke over all players or another player(s), if specified
offlineplayersCommandDescription=Lists previously connected players who are offline.
offlineplayersCommandUsage=/<command> [page]
offlineplayersCommandUsage1=/<command> [page]
offlineplayersCommandUsage1Description=Displays the first (or specified) page of offline players
offlinePlayersBusy=<primary>An offline player list is already being generated. Please try again shortly.
offlinePlayersChanged=<primary>Player activity changed the offline player list. Please try again.
offlinePlayersEmpty=<primary>There are no offline players to display.
offlinePlayersEntry=<secondary>{0} <primary>- <secondary>{1} <primary>- Last seen: <secondary>{2} ago
offlinePlayersEntryUnknown=<secondary>{0} <primary>- <secondary>{1} <primary>- Last seen: <secondary>Unknown
offlinePlayersHeader=<primary>Offline players ({2}) - Page {0}/{1}
offlinePlayersInvalidPage=<dark_red>Please specify a valid positive page number.
offlinePlayersLoading=<primary>Retrieving offline players, please wait...
offlinePlayersPageOutOfRange=<dark_red>Invalid page number. There are {0} pages available.
numberRequired=A number goes there, silly.
onlyDayNight=/time only supports day/night.
onlyPlayers=<dark_red>Only in-game players can use <secondary>{0}<dark_red>.
Expand Down
6 changes: 6 additions & 0 deletions Essentials/src/main/resources/plugin.yml
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,10 @@ commands:
description: May death rain upon them.
usage: /<command> [player]
aliases: [enuke]
offlineplayers:
description: Lists previously connected players who are offline.
usage: /<command> [page]
aliases: [eofflineplayers]
tpoffline:
description: Teleport to a player's last known logout location
usage: /<command> <player>
Expand Down Expand Up @@ -1094,6 +1098,8 @@ permissions:
description: Allows the bearer to use the specified command without cost
essentials.nuke:
description: Allows access to the /nuke command
essentials.offlineplayers:
description: Allows access to the /offlineplayers command
essentials.oversizedstacks:
description: Allows the bearer to spawn oversized stacks
essentials.pay:
Expand Down
Loading