Add daily emergency rescue and world-scoped home travel
This commit is contained in:
parent
48a40f0c90
commit
43998712f1
8 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
|
||||
|
|
|
|||
|
|
@ -26,7 +26,7 @@ final class OrganisationMenus implements Listener {
|
|||
public Inventory getInventory(){return inventory;}
|
||||
}
|
||||
OrganisationMenus(JavaPlugin plugin,HouseBridge bridge,Consumer<Player> mentat,Consumer<Player> travel,Consumer<Player> house,Consumer<Player> quests,Consumer<Player> exchange,Consumer<Player> spice,java.util.function.Predicate<Player> artwork){this.plugin=plugin;this.bridge=bridge;this.mentat=mentat;this.travel=travel;this.house=house;this.quests=quests;this.exchange=exchange;this.spice=spice;this.artwork=artwork;Bukkit.getPluginManager().registerEvents(this,plugin);}
|
||||
void console(Player p){var panel=panel(p,"Imperial Codex",0);if(p.getWorld().getName().equals("arrakis"))put(panel,28,"Spice buyers","Spacing Guild · Smuggler · P&O payout",Material.ORANGE_DYE,()->spice.accept(p));put(panel,34,"Exchange","Buy, sell and collect your purchases",Material.CHEST,()->exchange.accept(p));var exchangeIcon=new ItemStack(Material.CHEST);var exchangeMeta=exchangeIcon.getItemMeta();exchangeMeta.displayName(Component.text("Exchange",NamedTextColor.GOLD));exchangeMeta.lore(List.of(Component.text("Buy · Sell · Add held item",NamedTextColor.GRAY)));exchangeIcon.setItemMeta(exchangeMeta);panel.inventory.setItem(34,exchangeIcon);put(panel,31,"Mission journal","Personal Experience and Reputation",Material.WRITABLE_BOOK,()->quests.accept(p));put(panel,4,"Item lore archive","Preview the shared item lore cards",Material.WRITABLE_BOOK,()->lore(p));put(panel,19,"Clan","Your clan and Home Block",Material.GREEN_BANNER,()->open(p,"clans"));put(panel,22,"Company","Your companies and Home Blocks",Material.CYAN_BANNER,()->open(p,"companies"));put(panel,25,"POL","Your current political offices",Material.PURPLE_BANNER,()->open(p,"offices"));put(panel,37,"Your Mentat","Your personal briefing",Material.BOOK,()->mentat.accept(p));put(panel,40,"Spacing Guild","Transport and boarding windows",Material.COMPASS,()->travel.accept(p));put(panel,43,"Your House","Your allegiance and adviser",Material.NETHER_STAR,()->house.accept(p));close(panel,p);show(p,panel);}
|
||||
void console(Player p){var panel=panel(p,"Imperial Codex",0);put(panel,8,"Emergency rescue · 1,000 DM","Teleport to safety and heal · 24-hour cooldown",Material.TOTEM_OF_UNDYING,()->p.performCommand("duneess:rescue"));if(p.getWorld().getName().equals("arrakis"))put(panel,28,"Spice buyers","Spacing Guild · Smuggler · P&O payout",Material.ORANGE_DYE,()->spice.accept(p));put(panel,34,"Exchange","Buy, sell and collect your purchases",Material.CHEST,()->exchange.accept(p));var exchangeIcon=new ItemStack(Material.CHEST);var exchangeMeta=exchangeIcon.getItemMeta();exchangeMeta.displayName(Component.text("Exchange",NamedTextColor.GOLD));exchangeMeta.lore(List.of(Component.text("Buy · Sell · Add held item",NamedTextColor.GRAY)));exchangeIcon.setItemMeta(exchangeMeta);panel.inventory.setItem(34,exchangeIcon);put(panel,31,"Mission journal","Personal Experience and Reputation",Material.WRITABLE_BOOK,()->quests.accept(p));put(panel,4,"Item lore archive","Preview the shared item lore cards",Material.WRITABLE_BOOK,()->lore(p));put(panel,19,"Clan","Your clan and Home Block",Material.GREEN_BANNER,()->open(p,"clans"));put(panel,22,"Company","Your companies and Home Blocks",Material.CYAN_BANNER,()->open(p,"companies"));put(panel,25,"POL","Your current political offices",Material.PURPLE_BANNER,()->open(p,"offices"));put(panel,37,"Your Mentat","Your personal briefing",Material.BOOK,()->mentat.accept(p));put(panel,40,"Spacing Guild","Transport and boarding windows",Material.COMPASS,()->travel.accept(p));put(panel,43,"Your House","Your allegiance and adviser",Material.NETHER_STAR,()->house.accept(p));close(panel,p);show(p,panel);}
|
||||
void open(Player p,String kind){
|
||||
if(!busy.add(p.getUniqueId()))return;
|
||||
Bukkit.getScheduler().runTaskAsynchronously(plugin,()->{JsonObject data=null;try{data=bridge.organisations(p.getUniqueId());}catch(Exception ignored){}JsonObject result=data;if(!plugin.isEnabled())return;
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import {createBankTradePolicy} from './world-trade-governance.mjs';
|
||||
import {tradeWorld} from '../control-panel/public/world-trade-policy.mjs';
|
||||
import {createGuildSubsidies,verifyGuildSubsidy} from './guild-subsidy.mjs';
|
||||
import {currentGuildSurcharge,currentGuildDiscount} from './guild-tariff-policy.mjs';
|
||||
import {currentGuildSurcharge,currentGuildDiscount,standardGuildFare} from './guild-tariff-policy.mjs';
|
||||
import {createHash} from 'node:crypto';
|
||||
import {gameAuthorized,validUuid,json} from './game-link.mjs';
|
||||
import {boardingOpen} from './game-organisation-policy.mjs';
|
||||
|
|
@ -25,7 +25,7 @@ const fail=(message,status=409)=>{throw new BankError(message,status);};
|
|||
export function createGuildService(bank,{authority,resolve,allowArrakis=async()=>false,recordArrival=async()=>{},allowJourney=async()=>true,clock=Date.now,fareMinor=10000,surcharge=async()=>0,discount=async()=>0,allowSmuggling=null,smugglerFareMinor=fareMinor,prologueReady=async()=>true,subsidies=null}={}){
|
||||
if(!Number.isSafeInteger(fareMinor)||fareMinor<1||fareMinor>100000000||!Number.isSafeInteger(smugglerFareMinor)||smugglerFareMinor<1||smugglerFareMinor>100000000)throw Error('Invalid Guild fare');
|
||||
const payments=new PostbankPayments(bank,authority,{clock});
|
||||
async function quotedFare(user,store=bank,lock=false){const percent=await surcharge(clock()),reduction=await discount(user.faction,clock());if(!Number.isInteger(percent)||percent<0||percent>5||!Number.isInteger(reduction)||reduction<0||reduction>25)fail('The Guild tariff requires review.',503);const normal=Math.min(100000000,Math.max(1,Math.ceil(fareMinor*(100+percent)*(100-reduction)/10000))),offer=subsidies?await subsidies.quote(store,normal,reduction,lock):null;return {price:offer?.price??normal,offer};}
|
||||
async function quotedFare(user,store=bank,lock=false){const percent=await surcharge(clock()),reduction=await discount(user.faction,clock());const normal=standardGuildFare(fareMinor,percent,reduction);if(normal===null)fail('The Guild tariff requires review.',503);const offer=subsidies?await subsidies.quote(store,normal,reduction,lock):null;return {price:offer?.price??normal,offer};}
|
||||
const view=r=>({requestId:r.id,destination:r.destination,state:r.state,fareMinor:Number(r.fare_minor),expiresAt:Number(r.expires_at)});
|
||||
const readyForTravel=async(user,uuid,store=bank)=>await prologueReady(user,uuid)||!!await store.first("SELECT id FROM pb_guild_passages WHERE actor_id=? AND minecraft_uuid=? AND state='arrived' LIMIT 1",[user.id,uuid]);
|
||||
const allowed=async(user,destination)=>!!routes[user?.faction]&&(destination===routes[user.faction]||destination==='arrakis'&&await allowArrakis(user.faction,user));
|
||||
|
|
|
|||
|
|
@ -6,65 +6,90 @@ import {ordinaryPaymentAccount} from './postbank-recipient-policy.mjs';
|
|||
import {PostbankPayments} from './postbank-payments.mjs';
|
||||
import {BankError} from './postbank-service.mjs';
|
||||
import {NATIVE_SERVERS} from './native-server-scope.mjs';
|
||||
import {currentGuildSurcharge,currentGuildDiscount,standardGuildFare} from './guild-tariff-policy.mjs';
|
||||
|
||||
export const HOME_FARE_MINOR=2500,HOME_COOLDOWN_MS=15*60*1000;
|
||||
export const RESCUE_FARE_MINOR=100000,RESCUE_COOLDOWN_MS=24*60*60*1000;
|
||||
export const HOME_SCHEMA=`CREATE TABLE IF NOT EXISTS pb_home_passages(id CHAR(36) PRIMARY KEY,actor_id CHAR(36) NOT NULL,minecraft_uuid CHAR(36) NOT NULL,server VARCHAR(32) NOT NULL,destination_hash CHAR(64) NOT NULL,fingerprint CHAR(64) NOT NULL,source_id BIGINT UNSIGNED NOT NULL,target_id BIGINT UNSIGNED NOT NULL,state VARCHAR(16) NOT NULL,created_at BIGINT NOT NULL,arrived_at BIGINT NULL,INDEX home_actor(actor_id,state,arrived_at)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`;
|
||||
const accountSQL='SELECT a.*,c.entity_id,e.external_key,e.active entity_active,p.state package_state FROM pb_accounts a LEFT JOIN pb_clients c ON c.client_number=a.client_number LEFT JOIN pb_entities e ON e.id=c.entity_id LEFT JOIN pb_packages p ON p.id=a.package_id';
|
||||
const fail=(message,status=409)=>{throw new BankError(message,status);};
|
||||
export function createHomeTravelService(bank,{resolve,authority,clock=Date.now}={}){
|
||||
export function createHomeTravelService(bank,{resolve,authority,clock=Date.now,guildFare=10000}={}){
|
||||
const payments=new PostbankPayments(bank,authority,{clock});
|
||||
const view=r=>({ok:true,requestId:r.id,state:r.state,fareMinor:HOME_FARE_MINOR,cooldownUntil:r.arrived_at===null?null:Number(r.arrived_at)+HOME_COOLDOWN_MS});
|
||||
const view=(r,fare,cooldown)=>({ok:true,requestId:r.id,state:r.state,fareMinor:fare,cooldownUntil:r.arrived_at===null?null:Number(r.arrived_at)+cooldown});
|
||||
async function execute(input){
|
||||
const rescue=input.mode==='rescue';
|
||||
const worldHome=input.mode==='world';
|
||||
let fare=rescue?RESCUE_FARE_MINOR:HOME_FARE_MINOR;
|
||||
const cooldown=rescue||worldHome?RESCUE_COOLDOWN_MS:HOME_COOLDOWN_MS;
|
||||
const serviceName=rescue?'Emergency rescue':worldHome?'World home travel':'Home travel';
|
||||
// Keep old journal rows and their fingerprints readable during rolling upgrades.
|
||||
let server=rescue?input.server+':rescue':input.server;
|
||||
const user=await resolve(input.uuid);if(!user)fail('Link your active personal website account first.',403);
|
||||
let unreserved=false;try{return await bank.transaction(async tx=>{
|
||||
// One personal entity serialises /home on every backend, including different requests.
|
||||
await tx.first('SELECT id FROM pb_entities WHERE id=? FOR UPDATE',[entityId('person',user.id)]);
|
||||
let row=await tx.first('SELECT * FROM pb_home_passages WHERE id=? FOR UPDATE',[input.requestId]);
|
||||
const fingerprint=createHash('sha256').update(JSON.stringify([user.id,input.uuid,input.server,input.destinationHash])).digest('hex');
|
||||
if(worldHome&&row?.server.startsWith(input.server+':w')){
|
||||
server=row.server;
|
||||
fare=Number.parseInt(server.slice(input.server.length+2),36);
|
||||
}else if(worldHome&&!row){
|
||||
fare=typeof guildFare==='function'?await guildFare(user,input.uuid,clock()):guildFare;
|
||||
if(!Number.isSafeInteger(fare)||fare<1||fare>100000000)fail('The Guild tariff requires review.',503);
|
||||
server=input.server+':w'+fare.toString(36);
|
||||
}else if(worldHome||row&&row.server!==server){
|
||||
fail('This home travel reference was already used.');
|
||||
}
|
||||
if(!Number.isSafeInteger(fare)||fare<1||fare>100000000)fail('Home fare is unavailable.',503);
|
||||
const fingerprint=createHash('sha256').update(JSON.stringify([user.id,input.uuid,server,input.destinationHash])).digest('hex');
|
||||
if(row&&(row.actor_id!==user.id||row.fingerprint!==fingerprint))fail('This home travel reference was already used.');
|
||||
if(input.action==='reserve'){
|
||||
if(row)return{...view(row),replayed:true};
|
||||
if(row)return{...view(row,fare,cooldown),replayed:true};
|
||||
unreserved=true;
|
||||
const active=await tx.first("SELECT id FROM pb_home_passages WHERE actor_id=? AND state='pending' LIMIT 1",[user.id]);if(active)fail('Your previous home journey is still being completed. Reconnect to its server.');
|
||||
const last=await tx.first("SELECT arrived_at FROM pb_home_passages WHERE actor_id=? AND state='arrived' ORDER BY arrived_at DESC LIMIT 1",[user.id]);
|
||||
if(last&&Number(last.arrived_at)+HOME_COOLDOWN_MS>clock())fail('Home travel is on cooldown for '+Math.ceil((Number(last.arrived_at)+HOME_COOLDOWN_MS-clock())/1000)+' seconds.');
|
||||
const last=await tx.first("SELECT arrived_at FROM pb_home_passages WHERE actor_id=? AND state='arrived' AND CASE WHEN server LIKE '%:rescue' THEN 'rescue' WHEN server LIKE '%:w%' THEN 'world' ELSE 'normal' END=? ORDER BY arrived_at DESC LIMIT 1",[user.id,input.mode||'normal']);
|
||||
if(last&&Number(last.arrived_at)+cooldown>clock())fail(serviceName+' is on cooldown for '+Math.ceil((Number(last.arrived_at)+cooldown-clock())/1000)+' seconds.');
|
||||
const meta=await tx.query(accountSQL+" WHERE e.external_key=? AND e.kind='person' AND a.system_key IS NULL ORDER BY a.id",[user.id]),targetMeta=await tx.first("SELECT id FROM pb_accounts WHERE system_key='sys_game_treasury'");
|
||||
if(!targetMeta)fail('The game treasury is unavailable.',503);
|
||||
const ids=[...meta.map(a=>a.id),targetMeta.id].sort((a,b)=>Number(a)-Number(b)),rows=await tx.query(accountSQL+' WHERE a.id IN ('+ids.map(()=>'?').join(',')+') ORDER BY a.id FOR UPDATE',ids),rights=await authority(user,{bank:tx});
|
||||
const source=rows.find(a=>a.external_key===user.id&&ordinaryPaymentAccount(a)&&canDebitAccount(rights,a.entity_id,a.id)&&BigInt(a.balance_minor)-BigInt(a.reserved_minor)>=BigInt(HOME_FARE_MINOR)),target=rows.find(a=>String(a.id)===String(targetMeta.id));
|
||||
if(!source)fail('Home travel requires 25 DM available in your central personal bank account.');
|
||||
if(target?.state!=='active'||BigInt(target.balance_minor)+BigInt(HOME_FARE_MINOR)>9223372036854775807n)fail('The game treasury is unavailable.',503);
|
||||
row={id:input.requestId,actor_id:user.id,minecraft_uuid:input.uuid,server:input.server,destination_hash:input.destinationHash,fingerprint,source_id:source.id,target_id:target.id,state:'pending',created_at:clock(),arrived_at:null};
|
||||
await tx.query('UPDATE pb_accounts SET reserved_minor=reserved_minor+? WHERE id=?',[HOME_FARE_MINOR,source.id]);
|
||||
const source=rows.find(a=>a.external_key===user.id&&ordinaryPaymentAccount(a)&&canDebitAccount(rights,a.entity_id,a.id)&&BigInt(a.balance_minor)-BigInt(a.reserved_minor)>=BigInt(fare)),target=rows.find(a=>String(a.id)===String(targetMeta.id));
|
||||
if(!source)fail(serviceName+' requires '+(fare/100)+' DM available in your central personal bank account.');
|
||||
if(target?.state!=='active'||BigInt(target.balance_minor)+BigInt(fare)>9223372036854775807n)fail('The game treasury is unavailable.',503);
|
||||
row={id:input.requestId,actor_id:user.id,minecraft_uuid:input.uuid,server,destination_hash:input.destinationHash,fingerprint,source_id:source.id,target_id:target.id,state:'pending',created_at:clock(),arrived_at:null};
|
||||
await tx.query('UPDATE pb_accounts SET reserved_minor=reserved_minor+? WHERE id=?',[fare,source.id]);
|
||||
await tx.query('INSERT INTO pb_home_passages(id,actor_id,minecraft_uuid,server,destination_hash,fingerprint,source_id,target_id,state,created_at,arrived_at) VALUES(?,?,?,?,?,?,?,?,?,?,?)',Object.values(row));
|
||||
return view(row);
|
||||
return view(row,fare,cooldown);
|
||||
}
|
||||
if(!row)fail('This home journey has not been reserved.');
|
||||
if(row.state!=='pending')return{...view(row),replayed:true};
|
||||
if(row.state!=='pending')return{...view(row,fare,cooldown),replayed:true};
|
||||
const rows=await tx.query(accountSQL+' WHERE a.id IN (?,?) ORDER BY a.id FOR UPDATE',[row.source_id,row.target_id]),source=rows.find(a=>String(a.id)===String(row.source_id)),target=rows.find(a=>String(a.id)===String(row.target_id));
|
||||
if(!source||BigInt(source.reserved_minor)<BigInt(HOME_FARE_MINOR))fail('The home travel reservation needs review.',503);
|
||||
if(!source||BigInt(source.reserved_minor)<BigInt(fare))fail('The home travel reservation needs review.',503);
|
||||
if(input.action==='cancel'){
|
||||
await tx.query('UPDATE pb_accounts SET reserved_minor=reserved_minor-? WHERE id=?',[HOME_FARE_MINOR,source.id]);
|
||||
await tx.query("UPDATE pb_home_passages SET state='cancelled' WHERE id=?",[row.id]);row.state='cancelled';return view(row);
|
||||
await tx.query('UPDATE pb_accounts SET reserved_minor=reserved_minor-? WHERE id=?',[fare,source.id]);
|
||||
await tx.query("UPDATE pb_home_passages SET state='cancelled' WHERE id=?",[row.id]);row.state='cancelled';return view(row,fare,cooldown);
|
||||
}
|
||||
// Settle the accepted reservation, even if authority changed after actual arrival.
|
||||
// Holds never expire behind an unacknowledged physical teleport. The native journal retries.
|
||||
if(!target||target.system_key!=='sys_game_treasury')fail('The home receiving account needs review.',503);
|
||||
await tx.query("INSERT INTO pb_orders(id,actor_id,source_id,target_id,fingerprint,amount_minor,memo,mode,state,created_at) VALUES(?,?,?,?,?,?,?,'home','queued',?)",[row.id,user.id,row.source_id,row.target_id,row.fingerprint,HOME_FARE_MINOR,'Personal home travel',clock()]);
|
||||
await payments.post(tx,{id:row.id,actor_id:user.id,amount_minor:HOME_FARE_MINOR},source,target,true);
|
||||
row.state='arrived';row.arrived_at=clock();await tx.query("UPDATE pb_home_passages SET state='arrived',arrived_at=? WHERE id=?",[row.arrived_at,row.id]);return view(row);
|
||||
await tx.query("INSERT INTO pb_orders(id,actor_id,source_id,target_id,fingerprint,amount_minor,memo,mode,state,created_at) VALUES(?,?,?,?,?,?,?,'home','queued',?)",[row.id,user.id,row.source_id,row.target_id,row.fingerprint,fare,serviceName,clock()]);
|
||||
await payments.post(tx,{id:row.id,actor_id:user.id,amount_minor:fare},source,target,true);
|
||||
row.state='arrived';row.arrived_at=clock();await tx.query("UPDATE pb_home_passages SET state='arrived',arrived_at=? WHERE id=?",[row.arrived_at,row.id]);return view(row,fare,cooldown);
|
||||
});}catch(e){if(e instanceof BankError&&input.action==='reserve'&&unreserved)e.unreserved=true;throw e;}
|
||||
}
|
||||
return{execute};
|
||||
}
|
||||
export function createGameHomeAPI(db,bank,settings={},deps={}){
|
||||
const resolve=deps.resolve||(async uuid=>{const rows=await db.query("SELECT a.id,a.username,a.role FROM site_accounts a JOIN site_game_links l ON l.user_id=a.id WHERE LOWER(l.minecraft_uuid)=? AND a.password_hash NOT LIKE '!%' AND a.role NOT IN ('system_account','official_account','memorial')",[uuid]);return rows.length===1?rows[0]:null;});
|
||||
const service=deps.service||(bank?createHomeTravelService(bank,{resolve,authority:createPostbankAuthority(db,{bank})}):null);
|
||||
const guildFare=async(user,uuid,now)=>{
|
||||
const selection=await first(db,'SELECT faction FROM site_character_choices WHERE user_id=? AND LOWER(minecraft_uuid)=?',[user.id,uuid.toLowerCase()]);
|
||||
const [percent,reduction]=await Promise.all([currentGuildSurcharge(db,now),currentGuildDiscount(db,selection?.faction,now)]);
|
||||
return standardGuildFare(Number(settings.GUILD_FARE_MINOR||10000),percent,reduction);
|
||||
};
|
||||
const service=deps.service||(bank?createHomeTravelService(bank,{resolve,authority:createPostbankAuthority(db,{bank}),guildFare}):null);
|
||||
return async request=>{
|
||||
if(!gameAuthorized(request,settings))return json({message:'Unauthorized'},401);
|
||||
if(request.method!=='POST'||new URL(request.url).search||!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return json({message:'A JSON home action is required.'},400);
|
||||
let b;try{const reader=request.body.getReader(),chunks=[];let bytes=0;try{while(true){const {done,value}=await reader.read();if(done)break;bytes+=value.length;if(bytes>1024){await reader.cancel();return json({message:'Request too large'},413);}chunks.push(value);}}finally{reader.releaseLock();}b=JSON.parse(Buffer.concat(chunks).toString());}catch{return json({message:'Invalid home action'},400);}
|
||||
if(!b||Object.keys(b).sort().join(',')!=='action,destinationHash,requestId,server,uuid'||!['reserve','arrive','cancel'].includes(b.action)||!validUuid(b.uuid)||!validUuid(b.requestId)||!NATIVE_SERVERS.includes(b.server)||!/^[a-f0-9]{64}$/.test(b.destinationHash||''))return json({message:'Invalid home fields'},400);
|
||||
if(!b||Object.keys(b).sort().join(',')!==(['rescue','world'].includes(b.mode)?'action,destinationHash,mode,requestId,server,uuid':'action,destinationHash,requestId,server,uuid')||!['reserve','arrive','cancel'].includes(b.action)||!validUuid(b.uuid)||!validUuid(b.requestId)||!NATIVE_SERVERS.includes(b.server)||!/^[a-f0-9]{64}$/.test(b.destinationHash||''))return json({message:'Invalid home fields'},400);
|
||||
if(!service)return json({message:'The central bank is unavailable.'},503);
|
||||
try{return json(await service.execute(b));}catch(e){return json({message:e instanceof BankError?e.message:'Home travel could not be confirmed. Your journey remains available for retry.',unreserved:e instanceof BankError&&e.unreserved===true},e instanceof BankError?e.status||409:503);}
|
||||
};
|
||||
|
|
|
|||
|
|
@ -20,3 +20,10 @@ export async function currentGuildDiscount(base,house,now=Date.now()){
|
|||
const holder=await officeAuthority(db,{office:'spacing_guild'},{id:row.actor_id},now);if(holder?.termId===row.term_id)discount=Math.max(discount,payload.percent);
|
||||
}return discount;
|
||||
}
|
||||
|
||||
export function standardGuildFare(base,percent,reduction){
|
||||
if(!Number.isSafeInteger(base)||base<1||base>100000000||
|
||||
!Number.isInteger(percent)||percent<0||percent>5||
|
||||
!Number.isInteger(reduction)||reduction<0||reduction>25)return null;
|
||||
return Math.min(100000000,Math.max(1,Math.ceil(base*(100+percent)*(100-reduction)/10000)));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import test from 'node:test';import assert from 'node:assert/strict';import {randomUUID} from 'node:crypto';
|
||||
import {BankFixture} from './postbank-fixture.mjs';import {PostbankService} from '../node/postbank-service.mjs';import {BANK_VERSION} from '../node/postbank-catalogue.mjs';
|
||||
import {createHomeTravelService,createGameHomeAPI,HOME_SCHEMA,HOME_COOLDOWN_MS} from '../node/game-home.mjs';
|
||||
async function fixture(){
|
||||
import {createHomeTravelService,createGameHomeAPI,HOME_SCHEMA,HOME_COOLDOWN_MS,RESCUE_COOLDOWN_MS,RESCUE_FARE_MINOR} from '../node/game-home.mjs';
|
||||
async function fixture(guildFare){
|
||||
const db=new BankFixture();await db.query(HOME_SCHEMA.replace(/,INDEX home_actor\([^)]*\)/,'').replace(' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4',''));
|
||||
const user={id:randomUUID(),username:'traveller',uuid:randomUUID()},entity={kind:'person',key:user?.id,name:'traveller'};
|
||||
// Postbank's deterministic person entity is the lock shared by all backends.
|
||||
|
|
@ -12,7 +12,7 @@ async function fixture(){
|
|||
const source=(await db.first("SELECT id FROM pb_accounts WHERE type_code='102' AND system_key IS NULL")).id;
|
||||
await db.query('UPDATE pb_accounts SET balance_minor=20000 WHERE id=?',[source]);
|
||||
await db.query("INSERT INTO pb_accounts(system_key,type_code,display_name,balance_minor,reserved_minor,state,created_at) VALUES('sys_game_treasury','999','Game treasury',0,0,'active',0)");
|
||||
const service=createHomeTravelService(db,{authority,resolve:async()=>linked?user:null,clock:()=>now});
|
||||
const service=createHomeTravelService(db,{authority,resolve:async()=>linked?user:null,clock:()=>now,guildFare});
|
||||
return{db,user,service,source,input:()=>({action:'reserve',uuid:user.uuid,requestId:randomUUID(),server:'caladan',destinationHash:'a'.repeat(64)}),setTime:v=>now=v,revoke:()=>revoked=true,unlink:()=>linked=false,account:()=>db.first('SELECT balance_minor,reserved_minor FROM pb_accounts WHERE id=?',[source])};
|
||||
}
|
||||
test('home reserves central funds, settles exactly once and shares cooldown across backends',async()=>{
|
||||
|
|
@ -43,3 +43,34 @@ test('private home endpoint rejects account, price, world and cooldown overrides
|
|||
assert.equal((await api(request(b,'bad'))).status,401);assert.equal((await api(request(b))).status,200);
|
||||
for(const patch of [{fareMinor:0},{accountId:'1'},{world:'arrakis'},{cooldown:0},{server:'other'},{action:'expire'}])assert.equal((await api(request({...b,...patch}))).status,400);assert.equal(calls.length,1);
|
||||
});
|
||||
|
||||
test('rescue reserves 1000 DM, settles once and imposes a network-wide 24-hour cooldown',async()=>{
|
||||
const f=await fixture();
|
||||
try{
|
||||
await f.db.query('UPDATE pb_accounts SET balance_minor=200000 WHERE id=?',[f.source]);
|
||||
const q={...f.input(),mode:'rescue'};
|
||||
assert.equal((await f.service.execute(q)).fareMinor,RESCUE_FARE_MINOR);
|
||||
await assert.rejects(f.service.execute({...q,mode:'world',action:'arrive'}),/already used/);
|
||||
const result=await f.service.execute({...q,action:'arrive'});
|
||||
await f.service.execute({...q,action:'arrive'});
|
||||
assert.equal(result.cooldownUntil,1000000+RESCUE_COOLDOWN_MS);
|
||||
assert.deepEqual({...await f.account()},{balance_minor:100000,reserved_minor:0});
|
||||
await assert.rejects(f.service.execute({...f.input(),server:'arrakis',mode:'rescue'}),/cooldown/);
|
||||
assert.equal((await f.service.execute(f.input())).state,'pending');
|
||||
}finally{f.db.close();}
|
||||
});
|
||||
|
||||
test('world home uses the Guild tariff at reservation and retains it even if the tariff changes',async()=>{
|
||||
let quotedFare=13000;
|
||||
const f=await fixture(async()=>quotedFare);
|
||||
try{
|
||||
const q={...f.input(),mode:'world'};
|
||||
assert.equal((await f.service.execute(q)).fareMinor,13000);
|
||||
quotedFare=17000;
|
||||
const result=await f.service.execute({...q,action:'arrive'});
|
||||
assert.equal(result.fareMinor,13000);
|
||||
assert.equal(result.cooldownUntil,1000000+24*60*60*1000);
|
||||
assert.deepEqual({...await f.account()},{balance_minor:7000,reserved_minor:0});
|
||||
await assert.rejects(f.service.execute({...f.input(),mode:'world'}),/cooldown/);
|
||||
}finally{f.db.close();}
|
||||
});
|
||||
|
|
|
|||
Loading…
Reference in a new issue

Staff