forked from unimatrix/web
Add daily emergency rescue and world-scoped home travel
This commit is contained in:
parent
48a40f0c90
commit
43998712f1
3 changed files with 169 additions and 46 deletions
|
|
@ -27,7 +27,7 @@ final class EssentialsBasics implements CommandExecutor, TabCompleter, Listener
|
|||
}
|
||||
void register() {
|
||||
homeTravel=new PersonalHomeTravel(plugin);
|
||||
for(String name:List.of("home","sethome","delhome","homes","tpa","tpaccept","tpdeny","spawn","server","essentials")) {
|
||||
for(String name:List.of("home","rescue","sethome","delhome","homes","tpa","tpaccept","tpdeny","spawn","server","essentials")) {
|
||||
PluginCommand command=Objects.requireNonNull(plugin.getCommand(name));
|
||||
command.setExecutor(this); command.setTabCompleter(this);
|
||||
}
|
||||
|
|
@ -38,10 +38,29 @@ final class EssentialsBasics implements CommandExecutor, TabCompleter, Listener
|
|||
if(args.length>1 || !name.matches("[a-z0-9_-]{1,24}")) throw new IllegalArgumentException("Use a home name with 1–24 letters, numbers, underscores or hyphens.");
|
||||
return name;
|
||||
}
|
||||
private record HomeAddress(String name,boolean explicitWorld) {}
|
||||
private static HomeAddress address(Player player,String[] args){
|
||||
if(args.length!=2)return new HomeAddress(homeName(args),false);
|
||||
if(!player.getWorld().getName().equalsIgnoreCase(args[0])){
|
||||
throw new IllegalArgumentException("Use the Spacing Guild Navigator to reach "+args[0]+" first.");
|
||||
}
|
||||
return new HomeAddress(homeName(new String[]{args[1]}),true);
|
||||
}
|
||||
private String worldKey(Player player,String name){
|
||||
return "worldHomes."+player.getUniqueId()+"."+player.getWorld().getUID()+"."+name;
|
||||
}
|
||||
private Location location(Player player,String name){
|
||||
Location current=homes.getLocation(worldKey(player,name));
|
||||
return current!=null?current:homes.getLocation(key(player,name));
|
||||
}
|
||||
private String key(Player p,String name) { return p.getUniqueId()+"."+name; }
|
||||
private Set<String> names(Player p) {
|
||||
var section=homes.getConfigurationSection(p.getUniqueId().toString());
|
||||
return section==null?Set.of():section.getKeys(false);
|
||||
var world=homes.getConfigurationSection("worldHomes."+p.getUniqueId()+"."+p.getWorld().getUID());
|
||||
Set<String> result=new TreeSet<>();
|
||||
if(section!=null)result.addAll(section.getKeys(false));
|
||||
if(world!=null)result.addAll(world.getKeys(false));
|
||||
return result;
|
||||
}
|
||||
private void save() throws IOException {
|
||||
Path target=file.toPath(), temp=target.resolveSibling("homes.yml.tmp");
|
||||
|
|
@ -84,13 +103,19 @@ final class EssentialsBasics implements CommandExecutor, TabCompleter, Listener
|
|||
case "essentials" -> menu(p);
|
||||
case "homes" -> homeMenu(p);
|
||||
case "sethome" -> {
|
||||
String name=homeName(args), path=key(p,name);
|
||||
if(!homes.contains(path) && names(p).size()>=Math.max(1,plugin.getConfig().getInt("essentials.max-homes",3))) throw new IllegalArgumentException("Your home limit has been reached.");
|
||||
HomeAddress address=address(p,args);String name=address.name(),path=address.explicitWorld()?worldKey(p,name):key(p,name);
|
||||
if(!names(p).contains(name) && names(p).size()>=Math.max(1,plugin.getConfig().getInt("essentials.max-homes",3))) throw new IllegalArgumentException("Your home limit has been reached.");
|
||||
homes.set(path,p.getLocation()); save(); p.sendMessage("Home saved: "+name);
|
||||
}
|
||||
case "home" -> homeTravel.begin(p,homes.getLocation(key(p,homeName(args))));
|
||||
case "rescue" -> {if(args.length!=0)throw new IllegalArgumentException("Use /rescue for emergency travel.");homeTravel.rescue(p,location(p,"home"));}
|
||||
case "home" -> {
|
||||
HomeAddress address=address(p,args);
|
||||
Location destination=location(p,address.name());
|
||||
if(address.explicitWorld()||homes.contains(worldKey(p,address.name())))homeTravel.worldHome(p,destination);
|
||||
else homeTravel.begin(p,destination);
|
||||
}
|
||||
case "delhome" -> {
|
||||
String name=homeName(args),path=key(p,name);
|
||||
HomeAddress address=address(p,args);String name=address.name(),scoped=worldKey(p,name),path=address.explicitWorld()||homes.contains(scoped)?scoped:key(p,name);
|
||||
if(!homes.contains(path)) throw new IllegalArgumentException("That home does not exist.");
|
||||
homes.set(path,null); save(); p.sendMessage("Home removed: "+name);
|
||||
}
|
||||
|
|
@ -124,9 +149,12 @@ final class EssentialsBasics implements CommandExecutor, TabCompleter, Listener
|
|||
return true;
|
||||
}
|
||||
@Override public List<String> onTabComplete(CommandSender sender,Command command,String alias,String[] args) {
|
||||
if(!(sender instanceof Player p) || args.length!=1) return List.of();
|
||||
if(!(sender instanceof Player p))return List.of();
|
||||
if(args.length==2&&Set.of("home","delhome").contains(command.getName())&&p.getWorld().getName().equalsIgnoreCase(args[0]))return names(p).stream().filter(n->n.startsWith(args[1].toLowerCase(Locale.ROOT))).toList();
|
||||
if(args.length!=1)return List.of();
|
||||
Collection<String> values=switch(command.getName()) {
|
||||
case "home","delhome" -> names(p);
|
||||
case "home","delhome" -> {var choices=new TreeSet<>(names(p));choices.add(p.getWorld().getName());yield choices;}
|
||||
case "sethome" -> List.of(p.getWorld().getName());
|
||||
case "tpa" -> Bukkit.getOnlinePlayers().stream().filter(p::canSee).map(Player::getName).toList();
|
||||
case "server" -> List.of("arrakis","giedi_prime","caladan","kaitain","sigma_draconis_iv","spacing_guild");
|
||||
default -> List.of();
|
||||
|
|
|
|||
|
|
@ -30,28 +30,49 @@ final class PersonalHomeTravel implements Listener {
|
|||
try{Files.move(temp,file,StandardCopyOption.ATOMIC_MOVE,StandardCopyOption.REPLACE_EXISTING);}catch(AtomicMoveNotSupportedException e){Files.move(temp,file,StandardCopyOption.REPLACE_EXISTING);}
|
||||
}
|
||||
private boolean persist(){try{save();return true;}catch(Exception e){journal=YamlConfiguration.loadConfiguration(file.toFile());plugin.getLogger().warning("Home delivery journal could not be saved; no new travel will be started.");return false;}}
|
||||
void begin(Player p,Location destination){
|
||||
void begin(Player p,Location destination){begin(p,destination,"");}
|
||||
void worldHome(Player p,Location destination){begin(p,destination,"world");}
|
||||
void rescue(Player p,Location destination){
|
||||
if(destination==null||!p.getWorld().equals(destination.getWorld())||!safe(destination)){
|
||||
destination=p.getWorld().getSpawnLocation();
|
||||
}
|
||||
if(!safe(destination)){p.sendMessage("No safe rescue destination is available on this world.");return;}
|
||||
begin(p,destination,"rescue");
|
||||
}
|
||||
private static boolean safe(Location at){
|
||||
if(!valid(at)||!at.getWorld().isChunkLoaded(at.getBlockX()>>4,at.getBlockZ()>>4))return false;
|
||||
var feet=at.getBlock();
|
||||
var head=feet.getRelative(org.bukkit.block.BlockFace.UP);
|
||||
var floor=feet.getRelative(org.bukkit.block.BlockFace.DOWN);
|
||||
return feet.getType().isAir()&&head.getType().isAir()&&floor.getType().isSolid()&&
|
||||
!Set.of(Material.MAGMA_BLOCK,Material.CACTUS,Material.CAMPFIRE,Material.SOUL_CAMPFIRE).contains(floor.getType());
|
||||
}
|
||||
private void begin(Player p,Location destination,String mode){
|
||||
boolean rescue=mode.equals("rescue");
|
||||
if(!valid(destination)){p.sendMessage("That saved home is unavailable or outside the world's playable bounds.");return;}
|
||||
if(!p.getWorld().equals(destination.getWorld())){p.sendMessage("Travel to that world through the Guild first, then use /home.");return;}
|
||||
String id=p.getUniqueId().toString();if(waiting.containsKey(p.getUniqueId())||journal.contains(id)){p.sendMessage("Your home journey is already being completed.");return;}
|
||||
var connector=Bukkit.getPluginManager().getPlugin("JarvisTranslator");if(connector==null||!connector.isEnabled()){p.sendMessage("Central home travel is unavailable. No payment was made.");return;}
|
||||
UUID token=UUID.randomUUID(),world=p.getWorld().getUID();waiting.put(p.getUniqueId(),token);Location target=destination.clone();
|
||||
p.sendMessage("Home travel in 5 seconds · 25 DM · 15 minute cooldown.");
|
||||
Bukkit.getScheduler().runTaskLater(plugin,()->{
|
||||
if(!rescue)p.sendMessage(mode.equals("world")?"World home travel in 5 seconds · Spacing Guild tariff · 24-hour cooldown.":"Home travel in 5 seconds · 25 DM · 15 minute cooldown.");
|
||||
Runnable reserve=()->{
|
||||
if(!token.equals(waiting.remove(p.getUniqueId()))||!p.isOnline())return;
|
||||
if(!world.equals(p.getWorld().getUID())||p.isDead()||!valid(target)){p.sendMessage("Home travel cancelled. No payment was made.");return;}
|
||||
journal.set(id+".requestId",token.toString());journal.set(id+".destination",target);journal.set(id+".stage","reserve");
|
||||
journal.set(id+".requestId",token.toString());journal.set(id+".destination",target);journal.set(id+".stage","reserve");journal.set(id+".mode",mode);
|
||||
try{journal.set(id+".destinationHash",HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest((target.getWorld().getUID()+":"+target.getX()+":"+target.getY()+":"+target.getZ()+":"+target.getYaw()+":"+target.getPitch()).getBytes(StandardCharsets.UTF_8))));}catch(Exception e){throw new IllegalStateException(e);}
|
||||
if(persist())attempt(id);
|
||||
},100);
|
||||
};
|
||||
if(rescue)reserve.run();else Bukkit.getScheduler().runTaskLater(plugin,reserve,100);
|
||||
}
|
||||
private void recover(){for(String id:new HashSet<>(journal.getKeys(false)))attempt(id);}
|
||||
private void stage(String id,String value){journal.set(id+".stage",value);persist();}
|
||||
private void attempt(String id){
|
||||
if(!busy.add(id))return;
|
||||
String mode=journal.getString(id+".mode","");
|
||||
boolean rescue=mode.equals("rescue");
|
||||
String stage=journal.getString(id+".stage");Player player=Bukkit.getPlayer(UUID.fromString(id));
|
||||
// Keep a pre-payment instruction after a lost reply; retry it with exactly the same reference.
|
||||
var input=new JsonObject();input.addProperty("action",stage);input.addProperty("requestId",journal.getString(id+".requestId"));input.addProperty("destinationHash",journal.getString(id+".destinationHash"));
|
||||
var input=new JsonObject();input.addProperty("action",stage);input.addProperty("requestId",journal.getString(id+".requestId"));input.addProperty("destinationHash",journal.getString(id+".destinationHash"));if(!mode.isEmpty())input.addProperty("mode",mode);
|
||||
var connector=Bukkit.getPluginManager().getPlugin("JarvisTranslator");if(connector==null||!connector.isEnabled()){busy.remove(id);return;}
|
||||
Bukkit.getScheduler().runTaskAsynchronously(plugin,()->{
|
||||
JsonObject result=null;try{result=JsonParser.parseString((String)connector.getClass().getMethod("requestHome",UUID.class,String.class).invoke(connector,UUID.fromString(id),input.toString())).getAsJsonObject();}catch(Exception ignored){}
|
||||
|
|
@ -70,11 +91,17 @@ final class PersonalHomeTravel implements Listener {
|
|||
if(!state.equals("pending")){journal.set(id,null);persist();return;}
|
||||
if(!stage.equals("reserve"))return;
|
||||
Player current=Bukkit.getPlayer(UUID.fromString(id));Location target=journal.getLocation(id+".destination");
|
||||
if(current==null||!current.isOnline()||current.isDead()||!valid(target)||!current.getWorld().equals(target.getWorld())){stage(id,"cancel");return;}
|
||||
if(current==null||!current.isOnline()||current.isDead()||!valid(target)||rescue&&!safe(target)||!current.getWorld().equals(target.getWorld())){stage(id,"cancel");return;}
|
||||
// Keep the busy latch until the actual native result. Crash recovery re-delivers the same destination.
|
||||
current.teleportAsync(target).whenComplete((success,failure)->Bukkit.getScheduler().runTask(plugin,()->{
|
||||
stage(id,Boolean.TRUE.equals(success)&&failure==null?"arrive":"cancel");busy.remove(id);
|
||||
if(current.isOnline())current.sendMessage(Boolean.TRUE.equals(success)&&failure==null?"Home reached · 25 DM · 15 minute cooldown.":"Home travel failed. Your reservation will be released.");attempt(id);
|
||||
boolean arrived=Boolean.TRUE.equals(success)&&failure==null;
|
||||
stage(id,arrived?"arrive":"cancel");busy.remove(id);
|
||||
if(arrived&&rescue&¤t.isOnline()&&!current.isDead()){
|
||||
var health=current.getAttribute(org.bukkit.attribute.Attribute.MAX_HEALTH);
|
||||
if(health!=null)current.setHealth(health.getValue());
|
||||
current.setFireTicks(0);current.setFallDistance(0);
|
||||
}
|
||||
if(current.isOnline())current.sendMessage(arrived&&mode.equals("world")?"World home reached · "+String.format(Locale.ROOT,"%.2f DM",response.get("fareMinor").getAsLong()/100.0)+" · 24-hour cooldown.":arrived?(rescue?"Emergency rescue complete · 1,000 DM · 24-hour cooldown.":"Home reached · 25 DM · 15 minute cooldown."):"Teleport failed. Your reservation will be released.");attempt(id);
|
||||
}));
|
||||
teleporting=true;
|
||||
return;
|
||||
|
|
|
|||
|
|
@ -33,11 +33,16 @@ commands:
|
|||
essentials:
|
||||
description: Open DuneRealms Essentials
|
||||
permission: duneess.basics
|
||||
rescue:
|
||||
description: Emergency teleport and heal for 1,000 DM
|
||||
usage: /rescue
|
||||
home:
|
||||
description: Teleport to a saved home
|
||||
description: Teleport to a saved home on your current world
|
||||
usage: /home [world] [name]
|
||||
permission: duneess.basics
|
||||
sethome:
|
||||
description: Save a named home
|
||||
description: Save a named home on your current world
|
||||
usage: /sethome [world] [name]
|
||||
permission: duneess.basics
|
||||
delhome:
|
||||
description: Remove a named home
|
||||
|
|
|
|||
Loading…
Reference in a new issue

Staff