forked from unimatrix/web
115 lines
8.6 KiB
Java
115 lines
8.6 KiB
Java
package com.example.duneess;
|
|
|
|
import com.google.gson.*;
|
|
import org.bukkit.*;
|
|
import org.bukkit.configuration.file.YamlConfiguration;
|
|
import org.bukkit.entity.Player;
|
|
import org.bukkit.event.*;
|
|
import org.bukkit.event.player.PlayerQuitEvent;
|
|
import org.bukkit.plugin.java.JavaPlugin;
|
|
import java.nio.file.*;
|
|
import java.nio.charset.StandardCharsets;
|
|
import java.security.MessageDigest;
|
|
import java.util.*;
|
|
|
|
/** Same-world home travel. The existing connector owns central banking; this journal owns delivery. */
|
|
final class PersonalHomeTravel implements Listener {
|
|
private final JavaPlugin plugin;private final Path file;private YamlConfiguration journal;
|
|
private final Map<UUID,UUID> waiting=new HashMap<>();private final Set<String> busy=new HashSet<>();
|
|
PersonalHomeTravel(JavaPlugin plugin){
|
|
this.plugin=plugin;file=plugin.getDataFolder().toPath().resolve("home-journeys.yml");journal=YamlConfiguration.loadConfiguration(file.toFile());
|
|
Bukkit.getPluginManager().registerEvents(this,plugin);
|
|
Bukkit.getScheduler().runTaskTimer(plugin,this::recover,40,100);
|
|
}
|
|
static boolean valid(Location location){return location!=null&&location.getWorld()!=null&&Double.isFinite(location.getX())&&Double.isFinite(location.getY())&&Double.isFinite(location.getZ())&&location.getWorld().getWorldBorder().isInside(location)&&location.getY()>=location.getWorld().getMinHeight()&&location.getY()<location.getWorld().getMaxHeight();}
|
|
private void save()throws Exception{
|
|
Files.createDirectories(file.getParent());Path temp=file.resolveSibling("home-journeys.yml.tmp");
|
|
try(var channel=java.nio.channels.FileChannel.open(temp,StandardOpenOption.CREATE,StandardOpenOption.TRUNCATE_EXISTING,StandardOpenOption.WRITE)){
|
|
var bytes=StandardCharsets.UTF_8.encode(journal.saveToString());while(bytes.hasRemaining())channel.write(bytes);channel.force(true);
|
|
}
|
|
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){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();
|
|
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+".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);
|
|
};
|
|
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"));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){}
|
|
JsonObject response=result;Bukkit.getScheduler().runTask(plugin,()->{
|
|
boolean teleporting=false;
|
|
try{
|
|
if(response==null)return; // Unknown outcome stays durable and retries, never creates another payment.
|
|
if(response.has("rejectedStatus")){
|
|
int status=response.get("rejectedStatus").getAsInt();
|
|
// Only a definitive reserve refusal has no accepted liability. Settlement failures retain the journal.
|
|
if(stage.equals("reserve")&&response.has("unreserved")&&response.get("unreserved").getAsBoolean()){
|
|
if(player!=null&&player.isOnline())player.sendMessage(response.has("message")?response.get("message").getAsString():"Home travel was refused.");journal.set(id,null);persist();
|
|
}return;
|
|
}
|
|
String state=response.get("state").getAsString();
|
|
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)||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,()->{
|
|
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;
|
|
}finally{
|
|
if(!teleporting)busy.remove(id);
|
|
}
|
|
});
|
|
});
|
|
}
|
|
@EventHandler public void quit(PlayerQuitEvent event){waiting.remove(event.getPlayer().getUniqueId());}
|
|
}
|

Staff