Skip to content

Commit 2cb0651

Browse files
committed
Improve purge by using our own last login value stored in the db.
1 parent 68d5379 commit 2cb0651

File tree

8 files changed

+151
-38
lines changed

8 files changed

+151
-38
lines changed

src/main/java/world/bentobox/bentobox/BentoBox.java

+1
Original file line numberDiff line numberDiff line change
@@ -207,6 +207,7 @@ private void completeSetup(long loadTime) {
207207
registerListeners();
208208

209209
// Load islands from database - need to wait until all the worlds are loaded
210+
log("Loading islands from database...");
210211
try {
211212
islandsManager.load();
212213
} catch (Exception e) {

src/main/java/world/bentobox/bentobox/api/commands/admin/purge/AdminPurgeCommand.java

+59-22
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
import java.util.Iterator;
66
import java.util.List;
77
import java.util.Set;
8+
import java.util.UUID;
9+
import java.util.concurrent.CompletableFuture;
810

911
import org.bukkit.Bukkit;
1012
import org.bukkit.event.EventHandler;
@@ -21,8 +23,10 @@
2123

2224
public class AdminPurgeCommand extends CompositeCommand implements Listener {
2325

26+
private static final Long YEAR2000 = 946713600L;
2427
private int count;
2528
private boolean inPurge;
29+
private boolean scanning;
2630
private boolean toBeConfirmed;
2731
private Iterator<String> it;
2832
private User user;
@@ -47,6 +51,10 @@ public void setup() {
4751

4852
@Override
4953
public boolean canExecute(User user, String label, List<String> args) {
54+
if (scanning) {
55+
user.sendMessage("commands.admin.purge.scanning-in-progress");
56+
return false;
57+
}
5058
if (inPurge) {
5159
user.sendMessage("commands.admin.purge.purge-in-progress", TextVariables.LABEL, this.getTopLabel());
5260
return false;
@@ -75,13 +83,21 @@ public boolean execute(User user, String label, List<String> args) {
7583
user.sendMessage("commands.admin.purge.days-one-or-more");
7684
return false;
7785
}
78-
islands = getOldIslands(days);
79-
user.sendMessage("commands.admin.purge.purgable-islands", TextVariables.NUMBER, String.valueOf(islands.size()));
80-
if (!islands.isEmpty()) {
81-
toBeConfirmed = true;
82-
user.sendMessage("commands.admin.purge.confirm", TextVariables.LABEL, this.getTopLabel());
83-
return false;
84-
}
86+
user.sendMessage("commands.admin.purge.scanning");
87+
scanning = true;
88+
getOldIslands(days).thenAccept(islandSet -> {
89+
user.sendMessage("commands.admin.purge.purgable-islands", TextVariables.NUMBER,
90+
String.valueOf(islandSet.size()));
91+
if (!islandSet.isEmpty()) {
92+
toBeConfirmed = true;
93+
user.sendMessage("commands.admin.purge.confirm", TextVariables.LABEL, this.getTopLabel());
94+
islands = islandSet;
95+
} else {
96+
user.sendMessage("commands.admin.purge.none-found");
97+
}
98+
scanning = false;
99+
});
100+
85101
} catch (NumberFormatException e) {
86102
user.sendMessage("commands.admin.purge.number-error");
87103
return false;
@@ -125,40 +141,61 @@ void onIslandDeleted(IslandDeletedEvent e) {
125141
* @param days days
126142
* @return set of islands
127143
*/
128-
Set<String> getOldIslands(int days) {
129-
long currentTimeMillis = System.currentTimeMillis();
130-
long daysInMilliseconds = (long) days * 1000 * 3600 * 24;
131-
Set<String> oldIslands = new HashSet<>();
132-
144+
CompletableFuture<Set<String>> getOldIslands(int days) {
145+
CompletableFuture<Set<String>> result = new CompletableFuture<>();
133146
// Process islands in one pass, logging and adding to the set if applicable
134-
getPlugin().getIslands().getIslands().stream()
147+
getPlugin().getIslands().getIslandsASync().thenAccept(list -> {
148+
user.sendMessage("commands.admin.purge.total-islands", TextVariables.NUMBER, String.valueOf(list.size()));
149+
Set<String> oldIslands = new HashSet<>();
150+
list.stream()
135151
.filter(i -> !i.isSpawn()).filter(i -> !i.getPurgeProtected())
136152
.filter(i -> i.getWorld() != null) // to handle currently unloaded world islands
137-
.filter(i -> i.getWorld().equals(this.getWorld())).filter(Island::isOwned).filter(
138-
i -> i.getMemberSet().stream()
139-
.allMatch(member -> (currentTimeMillis
140-
- Bukkit.getOfflinePlayer(member).getLastPlayed()) > daysInMilliseconds))
153+
.filter(i -> i.getWorld().equals(this.getWorld())) // Island needs to be in this world
154+
.filter(Island::isOwned) // The island needs to be owned
155+
.filter(i -> i.getMemberSet().stream().allMatch(member -> checkLastLoginTimestamp(days, member)))
141156
.forEach(i -> {
142157
// Add the unique island ID to the set
143158
oldIslands.add(i.getUniqueId());
144-
BentoBox.getInstance().log("Will purge island at " + Util.xyz(i.getCenter().toVector()) + " in "
159+
getPlugin().log("Will purge island at " + Util.xyz(i.getCenter().toVector()) + " in "
145160
+ i.getWorld().getName());
146161
// Log each member's last login information
147162
i.getMemberSet().forEach(member -> {
148-
Date lastLogin = new Date(Bukkit.getOfflinePlayer(member).getLastPlayed());
163+
Long timestamp = getPlayers().getLastLoginTimestamp(member);
164+
Date lastLogin = new Date(timestamp);
149165
BentoBox.getInstance()
150166
.log("Player " + BentoBox.getInstance().getPlayers().getName(member)
151167
+ " last logged in "
152-
+ (int) ((currentTimeMillis - Bukkit.getOfflinePlayer(member).getLastPlayed())
153-
/ 1000 / 3600 / 24)
168+
+ (int) ((System.currentTimeMillis() - timestamp) / 1000 / 3600 / 24)
154169
+ " days ago. " + lastLogin);
155170
});
156171
BentoBox.getInstance().log("+-----------------------------------------+");
157172
});
173+
result.complete(oldIslands);
174+
});
175+
return result;
176+
}
158177

159-
return oldIslands;
178+
private boolean checkLastLoginTimestamp(int days, UUID member) {
179+
long daysInMilliseconds = days * 24L * 3600 * 1000; // Calculate days in milliseconds
180+
Long lastLoginTimestamp = getPlayers().getLastLoginTimestamp(member);
181+
// If no valid last login time is found or it's before the year 2000, try to fetch from Bukkit
182+
if (lastLoginTimestamp == null || lastLoginTimestamp < YEAR2000) {
183+
lastLoginTimestamp = Bukkit.getOfflinePlayer(member).getLastPlayed();
184+
185+
// If still invalid, set the current timestamp to mark the user for eventual purging
186+
if (lastLoginTimestamp < YEAR2000) {
187+
getPlayers().setLoginTimeStamp(member, System.currentTimeMillis());
188+
return false; // User will be purged in the future
189+
} else {
190+
// Otherwise, update the last login timestamp with the valid value from Bukkit
191+
getPlayers().setLoginTimeStamp(member, lastLoginTimestamp);
192+
}
193+
}
194+
// Check if the difference between now and the last login is greater than the allowed days
195+
return System.currentTimeMillis() - lastLoginTimestamp > daysInMilliseconds;
160196
}
161197

198+
162199
/**
163200
* @return the inPurge
164201
*/

src/main/java/world/bentobox/bentobox/database/AbstractDatabaseHandler.java

+21
Original file line numberDiff line numberDiff line change
@@ -134,10 +134,31 @@ protected AbstractDatabaseHandler() {}
134134
@Nullable
135135
public abstract T loadObject(@NonNull String uniqueId) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException, IntrospectionException, NoSuchMethodException;
136136

137+
/**
138+
* Loads all the records in this table and returns a list of them async
139+
* @return CompletableFuture List of <T>
140+
* @since 2.7.0
141+
*/
142+
public CompletableFuture<List<T>> loadObjectsASync() {
143+
CompletableFuture<List<T>> completableFuture = new CompletableFuture<>();
144+
145+
Bukkit.getScheduler().runTaskAsynchronously(BentoBox.getInstance(), () -> {
146+
try {
147+
completableFuture.complete(loadObjects()); // Complete the future with the result
148+
} catch (Exception e) {
149+
completableFuture.completeExceptionally(e); // Complete exceptionally if an error occurs
150+
plugin.logError("Failed to load objects asynchronously: " + e.getMessage());
151+
}
152+
});
153+
154+
return completableFuture;
155+
}
156+
137157
/**
138158
* Save T into the corresponding database
139159
*
140160
* @param instance that should be inserted into the database
161+
* @return completable future that is true if saved
141162
*/
142163
public abstract CompletableFuture<Boolean> saveObject(T instance) throws IllegalAccessException, InvocationTargetException, IntrospectionException ;
143164

src/main/java/world/bentobox/bentobox/database/Database.java

+7
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,13 @@ public static Set<Class<? extends DataObject>> getDataobjects() {
166166
return dataObjects;
167167
}
168168

169+
/**
170+
* Load all objects async
171+
* @return CompletableFuture<List<T>>
172+
*/
173+
public @NonNull CompletableFuture<List<T>> loadObjectsASync() {
174+
return handler.loadObjectsASync();
175+
}
169176

170177

171178
}

src/main/java/world/bentobox/bentobox/managers/IslandsManager.java

+10
Original file line numberDiff line numberDiff line change
@@ -458,6 +458,16 @@ public Collection<Island> getIslands() {
458458
return handler.loadObjects().stream().toList();
459459
}
460460

461+
/**
462+
* Loads all existing islands from the database without caching async
463+
*
464+
* @return CompletableFuture<List> of every island
465+
* @since 2.7.0
466+
*/
467+
public CompletableFuture<List<Island>> getIslandsASync() {
468+
return handler.loadObjectsASync();
469+
}
470+
461471
/**
462472
* Returns an <strong>unmodifiable collection</strong> of all the islands (even
463473
* those who may be unowned) in the specified world.

src/main/java/world/bentobox/bentobox/managers/PlayersManager.java

+17-5
Original file line numberDiff line numberDiff line change
@@ -423,21 +423,33 @@ public CompletableFuture<Boolean> savePlayer(UUID uuid) {
423423
/**
424424
* Records when the user last logged in. Called by the joinleave listener
425425
* @param user user
426+
* @since 2.7.0
426427
*/
427428
public void setLoginTimeStamp(User user) {
428429
if (user.isPlayer() && user.isOnline()) {
429-
Players p = this.getPlayer(user.getUniqueId());
430-
if (p != null) {
431-
p.setLastLogin(System.currentTimeMillis());
432-
this.savePlayer(user.getUniqueId());
433-
}
430+
setLoginTimeStamp(user.getUniqueId(), System.currentTimeMillis());
431+
}
432+
}
433+
434+
/**
435+
* Set the player's last login time to a timestamp
436+
* @param playerUUID player UUID
437+
* @param timestamp timestamp to set
438+
* @since 2.7.0
439+
*/
440+
public void setLoginTimeStamp(UUID playerUUID, long timestamp) {
441+
Players p = this.getPlayer(playerUUID);
442+
if (p != null) {
443+
p.setLastLogin(timestamp);
444+
this.savePlayer(playerUUID);
434445
}
435446
}
436447

437448
/**
438449
* Get the last login time stamp for this player
439450
* @param uuid player's UUID
440451
* @return timestamp or null if unknown or not recorded yet
452+
* @since 2.7.0
441453
*/
442454
@Nullable
443455
public Long getLastLoginTimestamp(UUID uuid) {

src/main/resources/locales/en-US.yml

+4
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,10 @@ commands:
9898
purgable-islands: '&a Found &b [number] &a purgable islands.'
9999
purge-in-progress: '&c Purging in progress. Use &b /[label] purge stop &c to
100100
cancel.'
101+
scanning: '&a Scanning islands in the database. This may take a while depending on how many you have...'
102+
scanning-in-progress: '&c Scanning in progress, please wait'
103+
none-found: '&c No islands found to purge.'
104+
total-islands: '&a You have [number] islands in your database in all worlds.'
101105
number-error: '&c Argument must be a number of days'
102106
confirm: '&d Type &b /[label] purge confirm &d to start purging'
103107
completed: '&a Purging stopped.'

src/test/java/world/bentobox/bentobox/api/commands/admin/purge/AdminPurgeCommandTest.java

+32-11
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,20 @@
66
import static org.mockito.ArgumentMatchers.any;
77
import static org.mockito.ArgumentMatchers.eq;
88
import static org.mockito.Mockito.mock;
9+
import static org.mockito.Mockito.never;
910
import static org.mockito.Mockito.times;
1011
import static org.mockito.Mockito.verify;
1112
import static org.mockito.Mockito.when;
1213

1314
import java.util.Collections;
15+
import java.util.List;
1416
import java.util.Optional;
1517
import java.util.Set;
1618
import java.util.UUID;
19+
import java.util.concurrent.CompletableFuture;
20+
import java.util.concurrent.ExecutionException;
21+
import java.util.concurrent.TimeUnit;
22+
import java.util.concurrent.TimeoutException;
1723

1824
import org.bukkit.Bukkit;
1925
import org.bukkit.Location;
@@ -38,6 +44,7 @@
3844
import world.bentobox.bentobox.api.addons.Addon;
3945
import world.bentobox.bentobox.api.commands.CompositeCommand;
4046
import world.bentobox.bentobox.api.events.island.IslandDeletedEvent;
47+
import world.bentobox.bentobox.api.localization.TextVariables;
4148
import world.bentobox.bentobox.api.user.User;
4249
import world.bentobox.bentobox.database.objects.Island;
4350
import world.bentobox.bentobox.managers.CommandsManager;
@@ -95,6 +102,7 @@ public void setUp() throws Exception {
95102
when(plugin.getIslands()).thenReturn(im);
96103
// No islands by default
97104
when(im.getIslands()).thenReturn(Collections.emptyList());
105+
when(im.getIslandsASync()).thenReturn(CompletableFuture.completedFuture(Collections.emptyList()));
98106

99107
// IWM
100108
IslandWorldManager iwm = mock(IslandWorldManager.class);
@@ -286,13 +294,13 @@ public void testExecuteUserStringListOfStringIslandsFound() {
286294
when(island.getOwner()).thenReturn(UUID.randomUUID());
287295
when(island.isOwned()).thenReturn(true);
288296
when(island.getMemberSet()).thenReturn(ImmutableSet.of(UUID.randomUUID()));
289-
when(im.getIslands()).thenReturn(Collections.singleton(island));
290-
OfflinePlayer op = mock(OfflinePlayer.class);
291-
when(op.getLastPlayed()).thenReturn(0L);
292-
when(Bukkit.getOfflinePlayer(any(UUID.class))).thenReturn(op);
293-
assertFalse(apc.execute(user, "", Collections.singletonList("10")));
294-
verify(user).sendMessage(eq("commands.admin.purge.purgable-islands"), eq("[number]"), eq("1"));
295-
verify(user).sendMessage(eq("commands.admin.purge.confirm"), eq("[label]"), eq("bsb"));
297+
when(im.getIslandsASync()).thenReturn(CompletableFuture.completedFuture(List.of(island)));
298+
when(pm.getLastLoginTimestamp(any())).thenReturn(962434800L);
299+
assertTrue(apc.execute(user, "", Collections.singletonList("10"))); // 10 days ago
300+
verify(user).sendMessage("commands.admin.purge.scanning");
301+
verify(user).sendMessage("commands.admin.purge.total-islands", "[number]", "1");
302+
verify(user, never()).sendMessage("commands.admin.purge.none-found");
303+
verify(user).sendMessage("commands.admin.purge.confirm", TextVariables.LABEL, "bsb");
296304
}
297305

298306

@@ -367,13 +375,26 @@ public void testSetUser() {
367375

368376
/**
369377
* Test method for {@link world.bentobox.bentobox.api.commands.admin.purge.AdminPurgeCommand#getOldIslands(int)}
378+
* @throws TimeoutException
379+
* @throws ExecutionException
380+
* @throws InterruptedException
370381
*/
371382
@Test
372-
public void testGetOldIslands() {
373-
assertTrue(apc.getOldIslands(10).isEmpty());
383+
public void testGetOldIslands() throws InterruptedException, ExecutionException, TimeoutException {
384+
assertTrue(apc.execute(user, "", Collections.singletonList("10"))); // 10 days ago
385+
// First, ensure that the result is empty
386+
CompletableFuture<Set<String>> result = apc.getOldIslands(10);
387+
Set<String> set = result.join();
388+
assertTrue(set.isEmpty());
389+
// Mocking Islands and their retrieval
390+
Island island1 = mock(Island.class);
374391
Island island2 = mock(Island.class);
375-
when(im.getIslands()).thenReturn(Set.of(island, island2));
376-
assertTrue(apc.getOldIslands(10).isEmpty());
392+
393+
when(im.getIslandsASync()).thenReturn(CompletableFuture.completedFuture(List.of(island1, island2)));
394+
// Now, check again after mocking islands
395+
CompletableFuture<Set<String>> futureWithIslands = apc.getOldIslands(10);
396+
assertTrue(futureWithIslands.get(5, TimeUnit.SECONDS).isEmpty()); // Adjust this assertion based on the expected behavior of getOldIslands
397+
377398
}
378399

379400
}

0 commit comments

Comments
 (0)