Skip to content
Merged
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
310 changes: 310 additions & 0 deletions ESPIONAGE.md

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ Players shape a world of provinces and titles, organise settlements and guilds,
- **National economies** — manage wealth and taxation, including income moving through relationships between members, nations, and overlords.
- **Settlements and guilds** — establish named cities and capitals and organise groups within a nation.
- **Military infrastructure** — construct forts, ports, airports, and train stations with `/faction construct <fort|port|airport|train_station> <name>`.
- **Espionage** — appoint a Spymaster, protect faction secrets, and obtain shared daily intelligence estimates. See [the development espionage guide](ESPIONAGE.md).
- **Campaign warfare** — pursue war goals through scheduled battles, player voting, warband participation, and campaign progression.

## A shared political world
Expand Down
26 changes: 22 additions & 4 deletions src/main/java/net/tfminecraft/simplefactions/SimpleFactions.java
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,7 @@ public class SimpleFactions extends JavaPlugin{
private final VehicleReclaimFeeListener vehicleReclaimFeeListener =
new VehicleReclaimFeeListener(vehicleFeeStore, vehicleFeeConfirmations, this::saveVehicleFees);
private boolean registrationFeeRegistered;
private boolean officeCharacterDeathRegistered;
private boolean vehicleIntegrationRegistered = false;
private boolean constructionFreezeRegistered;
private final PlayerEconomyManager playerEconomyManager = new PlayerEconomyManager();
Expand Down Expand Up @@ -279,6 +280,14 @@ public void onEnable() {
}
net.tfminecraft.simplefactions.inactivity.InactivityService.load();
db.loadFactions();
try {
net.tfminecraft.simplefactions.espionage.EspionageService.loadAptitudes(
getDataFolder().toPath().resolve("Cache/character-aptitudes.json"));
} catch (Exception error) {
getLogger().log(java.util.logging.Level.SEVERE, "Cannot load permanent character aptitudes; disabling SimpleFactions", error);
getServer().getPluginManager().disablePlugin(this);
return;
}
Comment thread
XxFran10xX marked this conversation as resolved.
getCommand(commands.cmd1).setExecutor(commands);
getCommand(commands.cmd2).setExecutor(commands);
getCommand(commands.cmd1).setTabCompleter(new TabCompletion());
Expand Down Expand Up @@ -372,10 +381,7 @@ public void onDisable() {
net.tfminecraft.simplefactions.war.battle.persistence.BattlePersistenceService.saveAll();
sessionManager.end();
net.tfminecraft.simplefactions.inactivity.InactivityService.save();
db.saveTimer(FactionManager.getTimer(), FactionManager.getDay());
for(Faction f : FactionManager.factions) {
db.saveFaction(f);
}
saveLoadedFactions();
for(War w : WarManager.get()){
db.saveWar(w);
}
Expand All @@ -386,7 +392,15 @@ public void onDisable() {
vehicleMaintenancePersistence.save();
}
}
void saveLoadedFactions() {
// An early enable failure must not overwrite partially restored faction state.
if (!FactionManager.isLoaded()) return;
db.saveTimer(FactionManager.getTimer(), FactionManager.getDay());
for (Faction faction : FactionManager.factions) db.saveFaction(faction);
}

public void loadConfigs() {
net.tfminecraft.simplefactions.espionage.SpecialPositionsConfigFile.load(this);
configLoader.loadConfig(new File(getDataFolder(), "config.yml"));
configLoader.loadWar(new File(getDataFolder(), "war.yml"));
VehiclesConfigLoader.load(new File(getDataFolder(), "vehicles.yml"));
Expand Down Expand Up @@ -678,6 +692,10 @@ private void registerRpCharactersIntegration() {
net.tfminecraft.simplefactions.prestige.MemberPlaytime.setProbe(
new net.tfminecraft.simplefactions.prestige.RpCharactersPlaytimeProbe());
net.tfminecraft.simplefactions.integration.rpcharacters.chat.RpCharactersChatIntegration.register();
if (!officeCharacterDeathRegistered) {
getServer().getPluginManager().registerEvents(new net.tfminecraft.simplefactions.espionage.OfficeCharacterDeathListener(), this);
officeCharacterDeathRegistered = true;
}
}

private void registerVehicleIntegrationHooks() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,7 @@ public void loadFactions() {
}
f.setFoundedAt(data.foundedAt != null ? data.foundedAt : System.currentTimeMillis()/1000L);
f.setCapitalMoves(data.capitalMoves != null ? data.capitalMoves : 0);
f.setEspionage(data.espionage);

if (data.settlements != null) {
f.getSettlementHandler().load(data.settlements);
Expand Down Expand Up @@ -312,6 +313,11 @@ public void loadFactions() {
* ===================================================== */

public void saveFaction(Faction f) {
saveFactionChecked(f);
}

/** Office mutations must not acknowledge success unless the faction save completed. */
public boolean saveFactionChecked(Faction f) {
try {
File file = new File("plugins/SimpleFactions/Data", f.getId() + ".json");

Expand Down Expand Up @@ -389,6 +395,7 @@ public void saveFaction(Faction f) {
data.rank = f.getRank() != null ? f.getRank().getId() : null;
data.foundedAt = f.getFoundedAt();
data.capitalMoves = f.getCapitalMoves();
data.espionage = f.getEspionage();

// --- Guild ---
for (Guild g : f.getGuildHandler().getGuilds()) {
Expand Down Expand Up @@ -514,10 +521,12 @@ public void saveFaction(Faction f) {
data.warReparationsObligations.add(obligationData);
}

JsonUtil.writeJson(file, data);
JsonUtil.writeJsonAtomic(file, data);
return true;

} catch (Exception e) {
e.printStackTrace();
return false;
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package net.tfminecraft.simplefactions.database;

import net.tfminecraft.simplefactions.espionage.EspionageState;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
Expand All @@ -8,6 +9,7 @@
import com.google.gson.annotations.SerializedName;

public class FactionData {
public EspionageState espionage;
public String id;
public String name;
public String rgb;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,25 @@ public static void writeJson(File file, Object data) throws IOException {
GSON.toJson(data, w);
}
}

/** Stage a complete save beside the destination so failed writes keep the previous data. */
public static void writeJsonAtomic(File file, Object data) throws IOException {
var destination = file.toPath().toAbsolutePath();
var pending = java.nio.file.Files.createFile(destination.resolveSibling(file.getName() + "." + java.util.UUID.randomUUID() + ".tmp"));
try {
if (java.nio.file.Files.exists(destination)
&& java.nio.file.Files.getFileAttributeView(destination, java.nio.file.attribute.PosixFileAttributeView.class) != null) {
java.nio.file.Files.setPosixFilePermissions(pending, java.nio.file.Files.getPosixFilePermissions(destination));
}
java.nio.file.Files.writeString(pending, GSON.toJson(data));
try {
java.nio.file.Files.move(pending, destination, java.nio.file.StandardCopyOption.REPLACE_EXISTING,
java.nio.file.StandardCopyOption.ATOMIC_MOVE);
} catch (java.nio.file.AtomicMoveNotSupportedException ignored) {
java.nio.file.Files.move(pending, destination, java.nio.file.StandardCopyOption.REPLACE_EXISTING);
}
} finally {
java.nio.file.Files.deleteIfExists(pending);
}
}
}
6 changes: 6 additions & 0 deletions src/main/java/net/tfminecraft/simplefactions/enums/SFGUI.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ public enum SFGUI {
FACTION_VIEW,
FACTION_LIST,
FACTION_GUILDS,
SPECIAL_POSITIONS,
SPYMASTER_VIEW,
SPYMASTER_SETTINGS,
SPYMASTER_SELECT,
TIER_VIEW,
TITLE_VIEW,
TITLE_TYPE_VIEW,
Expand Down Expand Up @@ -46,6 +50,8 @@ public enum SFGUI {
FEE_CATEGORY_VIEW,
FEE_VEHICLE_VIEW,
LEDGER_VIEW,
FOREIGN_LEDGER_VIEW,
FOREIGN_POSITIONS_VIEW,
COUNCIL_VIEW,
COUNCIL_SELECT,
ELECTION_VIEW,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package net.tfminecraft.simplefactions.espionage;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Supplier;
import com.google.gson.reflect.TypeToken;
import net.tfminecraft.simplefactions.database.JsonUtil;

/** Character identity, rather than faction membership, owns the permanent roll. */
public final class CharacterAptitudes {
private final Path file;
private final Map<String, Integer> aptitudes = new LinkedHashMap<>();

public CharacterAptitudes(Path file) { this.file = file; }

public void load() throws IOException {
aptitudes.clear();
if (!Files.exists(file)) return;
Map<String, Integer> loaded = JsonUtil.GSON.fromJson(Files.readString(file),
new TypeToken<Map<String, Integer>>() {}.getType());
if (loaded == null) throw new IOException("Empty character aptitude registry: " + file);
loaded.forEach((key, value) -> {
if (key != null && value != null) aptitudes.put(key, EspionageMath.clamp(value, 0, 100));
});
}

public void remember(String characterId, int aptitude) {
if (characterId != null && !characterId.isBlank())
aptitudes.putIfAbsent(characterId, EspionageMath.clamp(aptitude, 0, 100));
}

public int aptitude(String characterId, Supplier<Integer> roll) throws IOException {
if (characterId == null || characterId.isBlank()) throw new IllegalArgumentException("Missing character identity");
Integer existing = aptitudes.get(characterId);
if (existing != null) return existing;
int result = EspionageMath.clamp(roll.get(), 0, 100);
aptitudes.put(characterId, result);
try { save(); }
catch (IOException error) { aptitudes.remove(characterId); throw error; }
return result;
}

public void save() throws IOException {
Files.createDirectories(file.getParent());
Path pending = file.resolveSibling(file.getFileName() + ".tmp");
Files.writeString(pending, JsonUtil.GSON.toJson(aptitudes));
try { Files.move(pending, file, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); }
catch (java.nio.file.AtomicMoveNotSupportedException ignored) {
Files.move(pending, file, StandardCopyOption.REPLACE_EXISTING);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
package net.tfminecraft.simplefactions.espionage;

import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import org.bukkit.Bukkit;
import net.tfminecraft.rpcharacters.managers.PlayerManager;
import net.tfminecraft.simplefactions.database.JsonUtil;
import com.google.gson.JsonObject;

/** Offline names are read without loading or modifying RPCharacters player state. */
public final class CharacterNames {
private record Cached(String name, long expires) {}
private static final Map<String, Cached> cache = new java.util.concurrent.ConcurrentHashMap<>();
private CharacterNames() {}

public static String display(org.bukkit.entity.Player viewer, String account) {
String character = of(account);
return EspionageService.bypasses(viewer) ? character + " \u00a77(" + account + ")" : character;
}

public static String display(org.bukkit.entity.Player viewer, String account,
net.tfminecraft.simplefactions.objects.Faction faction) {
if (!OfficeCharacters.enabled("RPCharacters") || EspionageService.canViewExact(viewer, faction))
return display(viewer, account);
return forForeign(account);
}

/** A missing active character must not expose account identity in foreign reports. */
public static String forForeign(String account) {
String name = activeName(account);
return name == null ? "Unknown" : name;
}

/** Exact account names take precedence; ambiguous character names never pick a player arbitrarily. */
public static org.bukkit.entity.Player resolveOnline(org.bukkit.entity.Player sender, String input) {
String query = input.strip();
if (query.length() >= 2 && query.startsWith("\"") && query.endsWith("\""))
query = query.substring(1, query.length() - 1).strip();
var result = resolve(query, Bukkit.getOnlinePlayers(), player -> of(player.getName()));
if (result.ambiguous()) sender.sendMessage("\u00a7cSeveral characters share that name. Use their Minecraft name.");
else if (result.player() == null) sender.sendMessage("\u00a7cNo online player found by that character or Minecraft name.");
return result.player();
}

static Resolution resolve(String query, java.util.Collection<? extends org.bukkit.entity.Player> players,
java.util.function.Function<org.bukkit.entity.Player, String> names) {
for (var player : players) if (player.getName().equalsIgnoreCase(query)) return new Resolution(player, false);
var matches = players.stream().filter(player -> org.bukkit.ChatColor.stripColor(names.apply(player))
.equalsIgnoreCase(query)).toList();
return new Resolution(matches.size() == 1 ? matches.getFirst() : null, matches.size() > 1);
}

record Resolution(org.bukkit.entity.Player player, boolean ambiguous) {}

/** Bukkit replaces only the current argument, so return the untyped suffix of a full name. */
public static java.util.List<String> inviteCompletions(java.util.Collection<String> names, String[] args) {
if (args.length < 2) return java.util.List.of();
int skip = args.length - 2;
String prefix = String.join(" ", java.util.Arrays.copyOfRange(args, 1, args.length));
return names.stream().filter(java.util.Objects::nonNull).map(org.bukkit.ChatColor::stripColor).distinct()
.filter(name -> name.regionMatches(true, 0, prefix, 0, prefix.length()))
Comment thread
coderabbitai[bot] marked this conversation as resolved.
.map(name -> name.split(" "))
.filter(words -> words.length > skip)
.map(words -> String.join(" ", java.util.Arrays.copyOfRange(words, skip, words.length)))
.toList();
}

public static String of(String playerName) {
String name = activeName(playerName);
return name == null ? playerName : name;
}

private static String activeName(String playerName) {
if (playerName == null) return "Unknown";
if (!OfficeCharacters.enabled("RPCharacters")) return playerName;
var player = Bukkit.getPlayerExact(playerName);
if (player != null) {
var data = PlayerManager.get(player);
var character = data == null ? null : data.getActiveCharacter();
if (character != null) return character.getName();
}
Cached cached = cache.get(playerName);
if (cached != null && cached.expires > System.currentTimeMillis()) return cached.name;
String result = null;
var plugin = Bukkit.getPluginManager().getPlugin("RPCharacters");
Path folder = plugin.getDataFolder().toPath().resolve("data/characterdata")
.resolve(Bukkit.getOfflinePlayer(playerName).getUniqueId().toString());
if (Files.isDirectory(folder)) {
try (var files = Files.list(folder)) {
for (Path file : files.filter(path -> path.toString().endsWith(".json")).sorted().toList()) {
JsonObject json = JsonUtil.GSON.fromJson(Files.readString(file), JsonObject.class);
if (json != null && json.has("active") && json.get("active").getAsBoolean() && json.has("name")) {
result = json.get("name").getAsString();
break;
}
}
} catch (java.io.IOException | com.google.gson.JsonParseException | IllegalStateException ignored) {
// Cache the absence too; account-oriented callers supply their own fallback.
}
}
cache.put(playerName, new Cached(result, System.currentTimeMillis() + 30_000));
return result;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package net.tfminecraft.simplefactions.espionage;

import java.util.function.Supplier;
import org.bukkit.entity.Player;

/** Only a command creating a faction/guild menu can request new daily intelligence. */
public final class CommandIntelligence {
private static final ThreadLocal<Context> current = new ThreadLocal<>();
private static final class Context {
final Player player;
boolean gathered;
Context(Player player) { this.player = player; }
}
private CommandIntelligence() {}

public static boolean execute(Player player, Supplier<Boolean> command) {
Context previous = current.get();
current.set(new Context(player));
try { return command.get(); }
finally {
if (previous == null) current.remove();
else current.set(previous);
}
}

public static void beforeMenu() {
Context context = current.get();
if (context != null && context.player != null && !context.gathered) {
context.gathered = true;
EspionageService.refreshReports(context.player);
}
}
}
Loading
Loading