Skip to content

Commit

Permalink
Merge branch 'city-cost'
Browse files Browse the repository at this point in the history
  • Loading branch information
xdnw committed Feb 28, 2025
2 parents ecd2458 + 010e4b2 commit b9e0875
Show file tree
Hide file tree
Showing 13 changed files with 142 additions and 138 deletions.
11 changes: 6 additions & 5 deletions src/main/java/link/locutus/discord/apiv1/enums/ResourceType.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import link.locutus.discord.apiv1.enums.city.project.Project;
import link.locutus.discord.apiv1.enums.city.project.Projects;
import link.locutus.discord.db.entities.DBNation;
import link.locutus.discord.pnw.NationOrAlliance;
import link.locutus.discord.util.IOUtil;
import link.locutus.discord.util.MathMan;
import link.locutus.discord.util.StringMan;
Expand Down Expand Up @@ -134,13 +135,13 @@ public static Map<ResourceType, Double> roundResources(Map<ResourceType, Double>
return copy;
}

public static String resourcesToJson(String receiver, boolean isNation, Map<ResourceType, Double> rss, String note) {
public static Map<String, String> resourcesToJson(NationOrAlliance receiver, Map<ResourceType, Double> rss, String note) {
Map<String, String> post = new LinkedHashMap<>();
if (isNation) {
post.put("withrecipient", receiver);
if (receiver.isNation()) {
post.put("withrecipient", receiver.getName());
post.put("withtype", "Nation");
} else {
post.put("withrecipient", "" + receiver);
post.put("withrecipient", receiver.getName());
post.put("withtype", "Alliance");
}
for (ResourceType type : values) {
Expand All @@ -156,7 +157,7 @@ public static String resourcesToJson(String receiver, boolean isNation, Map<Reso
// for (Map.Entry<String, String> entry : post.entrySet()) {
// entry.setValue("\"" + entry.getValue() + "\"");
// }
return WebUtil.GSON.toJson(post);
return post;
}

public static Map<ResourceType, Double> parseResources(String arg) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -384,7 +384,7 @@ private void handleWarRoomSync(Guild guild, User msgUser, IMessageIO io, String

Category category = GuildMessageChannel.getParentCategory();
if (category == null) return;
if (!category.getName().startsWith("warcat")) return;
if (!category.getName().toLowerCase().startsWith("warcat")) return;
GuildDB db = Locutus.imp().getGuildDB(guild);
if (db == null) return;
if (!db.isWhitelisted() && db.getOrNull(GuildKey.ENABLE_WAR_ROOMS) != Boolean.TRUE) return;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -835,7 +835,7 @@ private IllegalArgumentException throwUnknownCommand(String command) {
}
full.append(")");
}
BiFunction<T, Object[], Object> format = (object, paramVals) -> command.call(object, store, paramVals);
BiFunction<T, Object[], Object> format = (object, paramVals) -> object == null ? null : command.call(object, store, paramVals);
if (isResolved) {
Object[] argArr = resolved.apply(null);
return TypedFunction.createParents(command.getReturnType(), f -> format.apply(f, argArr), "{" + full.toString() + "}", null);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ public static Category category(@Me Guild guild, String category, @Default Param
Filter filter = param == null ? null : param.getAnnotation(Filter.class);
if (filter != null) {
categories = new ArrayList<>(categories);
categories.removeIf(f -> !f.getName().matches(filter.value()));
categories.removeIf(f -> !f.getName().toLowerCase().matches(filter.value()));
}
if (categories.isEmpty()) {
if (MathMan.isInteger(category)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -307,7 +307,8 @@ public String syncWarrooms(@Me IMessageIO io, @Me JSONObject command, @Me GuildD
}
long diff = System.currentTimeMillis() - start;
io.create().append("Sync war rooms complete. Took: " + diff + "ms\n" +
"See the attached log file for task output").file("warcat.txt", full.toString()).send();
"See the attached log file for task output. To sort rooms, see: " + CM.war.room.sort.cmd.toSlashMention())
.file("warcat.txt", full.toString()).send();

return null;
}
Expand Down Expand Up @@ -2759,7 +2760,7 @@ public String purgeWarRooms( // war room delete_all
iter.remove();
}
for (Category category : categories) {
if (category.getName().startsWith("warcat-")) {
if (category.getName().toLowerCase().startsWith("warcat-")) {
RateLimitUtil.queue(category.delete());
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ public String onCommand(Guild guild, IMessageIO channel, User author, DBNation m
iter.remove();
}
for (Category category : categories) {
if (category.getName().startsWith("warcat-")) {
if (category.getName().toLowerCase().startsWith("warcat-")) {
RateLimitUtil.queue(category.delete());
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -352,7 +352,7 @@ public static NationFilter getFilter(GuildDB db) {
}

public static CityRanges getRangeFromCategory(Category category) {
String[] split = category.getName().split("-", 2);
String[] split = category.getName().toLowerCase().split("-", 2);
if (split.length == 2) {
String filterStr = split[1];
if (filterStr.charAt(0) == 'c') {
Expand Down
32 changes: 32 additions & 0 deletions src/main/java/link/locutus/discord/db/entities/DBNation.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import link.locutus.discord.commands.manager.v2.binding.bindings.TypedFunction;
import link.locutus.discord.commands.manager.v2.command.*;
import link.locutus.discord.commands.manager.v2.impl.discord.permission.RolePermission;
import link.locutus.discord.commands.manager.v2.impl.pw.binding.NationAttributeDouble;
import link.locutus.discord.commands.manager.v2.impl.pw.refs.CM;
import link.locutus.discord.commands.manager.v2.impl.pw.NationFilter;
import link.locutus.discord.commands.manager.v2.impl.pw.TaxRate;
Expand Down Expand Up @@ -4557,6 +4558,37 @@ public double maxCityInfra() {
return maxInfra;
}

@Command(desc = "Sum of city attribute for specific cities this nation has")
public double getTotal(@NoFormat TypedFunction<DBCity, Double> attribute, @NoFormat @Default Predicate<DBCity> filter) {
Collection<DBCity> cities = this._getCitiesV3().values();
return cities.stream().filter(f -> filter == null || filter.test(f)).mapToDouble(attribute::apply).sum();
}

@Command(desc = "Average of city attribute for specific cities in nation")
public double getAverage(@NoFormat TypedFunction<DBCity, Double> attribute, @NoFormat @Default Predicate<DBCity> filter) {
Collection<DBCity> cities = this._getCitiesV3().values();
return cities.stream().filter(f -> filter == null || filter.test(f)).mapToDouble(attribute::apply).average().orElse(0);
}

@Command(desc = "Returns the average value of the given attribute per another attribute (such as infra)")
public double getAveragePer(@NoFormat TypedFunction<DBCity, Double> attribute, @NoFormat TypedFunction<DBCity, Double> per, @Default Predicate<DBCity> filter) {
Collection<DBCity> cities = this._getCitiesV3().values();
double total = 0;
double perTotal = 0;
for (DBCity city : cities) {
if (filter != null && !filter.test(city)) continue;
total += attribute.apply(city);
perTotal += per.apply(city);
}
return total / perTotal;
}

@Command(desc = "Count of cities in nation matching a filter")
public int countCities(@NoFormat @Default Predicate<DBCity> filter) {
if (filter == null) return getCities();
return (int) _getCitiesV3().values().stream().filter(filter).count();
}

@Command(desc = "The highest land level in their cities")
public double maxCityLand() {
double maxLand = 0;
Expand Down
4 changes: 0 additions & 4 deletions src/main/java/link/locutus/discord/util/PW.java
Original file line number Diff line number Diff line change
Expand Up @@ -1495,10 +1495,6 @@ public Integer apply(Double min, Double max) {
};
}

public static String getPostScript(String name, boolean nation, Map<ResourceType, Double> rss, String note) {
return ResourceType.resourcesToJson(name, nation, rss, note);
}

public static double getOdds(double attStrength, double defStrength, int success) {
attStrength = Math.pow(attStrength, 0.75);
defStrength = Math.pow(defStrength, 0.75);
Expand Down
32 changes: 28 additions & 4 deletions src/main/java/link/locutus/discord/util/offshore/Auth.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,7 @@
import link.locutus.discord.apiv3.enums.AlliancePermission;
import link.locutus.discord.config.Settings;
import link.locutus.discord.db.GuildDB;
import link.locutus.discord.db.entities.DBAlliancePosition;
import link.locutus.discord.db.entities.PendingTreaty;
import link.locutus.discord.db.entities.TaxBracket;
import link.locutus.discord.db.entities.DBNation;
import link.locutus.discord.db.entities.*;
import link.locutus.discord.network.IProxy;
import link.locutus.discord.network.PassthroughProxy;
import link.locutus.discord.pnw.NationOrAlliance;
Expand Down Expand Up @@ -739,6 +736,33 @@ public Set<TradeResult> call() throws Exception {
return login ? PW.withLogin(task, auth) : task.call();
}

public String withdrawResources(DBAlliance alliance, NationOrAlliance receiver, double[] amount, String note) {
Map<String, String> post = ResourceType.resourcesToJson(receiver, ResourceType.resourcesToMap(amount), note);
int fromBank = alliance.getAlliance_id();

return PW.withLogin(() -> {
String result = readStringFromURL(PagePriority.BANK_DEPOSIT, "" + Settings.INSTANCE.PNW_URL() + "/alliance/id=" + fromBank + "&display=bank", emptyMap());
Document dom = Jsoup.parse(result);
String token = dom.select("input[name=token]").attr("value");
post.put("token", token);
StringBuilder response = new StringBuilder();

result = readStringFromURL(PagePriority.TOKEN, "" + Settings.INSTANCE.PNW_URL() + "/alliance/id=" + fromBank + "&display=bank", post);
dom = Jsoup.parse(result);
for (Element element : dom.getElementsByClass("alert")) {
String text = element.text();
if (text.startsWith("Player Advertisement by ")) {
continue;
}
response.append('\n').append(text);
}
if (response.length() == 0) {
return "(not output)";
}
return response.toString();
}, this);
}

///////////////////////

public enum TradeResultType {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1449,7 +1449,11 @@ public TransferResult transferSafe(DBNation nation, Map<ResourceType, Double> tr

public TransferResult transfer(DBNation nation, Map<ResourceType, Double> transfer, String note, Map<DBAlliance, Map<ResourceType, Double>> transferRoute) {
synchronized (BANK_LOCK) {
return transfer(null, nation, transfer, note, transferRoute);
Auth auth = null;
if (Settings.USE_V2) {
auth = getAlliance().getAuth(AlliancePermission.WITHDRAW_BANK);
}
return transfer(auth, nation, transfer, note, transferRoute);
}
}

Expand Down Expand Up @@ -1602,22 +1606,21 @@ public TransferResult transferUnsafe(Auth auth, NationOrAlliance receiver, Map<R
// todo test if game is still down
WebRoot web = WebRoot.getInstance();

BankRequestHandler handler = web.getLegacyBankHandler();
// BankRequestHandler handler = web.getLegacyBankHandler();
if (auth.getNationId() != Locutus.loader().getNationId() || auth.getAllianceId() != allianceId) {
throw new IllegalArgumentException("Game API is down currently");
}

UUID uuid = UUID.randomUUID();
Future<String> request = handler.addRequest(uuid, receiver, ResourceType.resourcesToArray(transfer), note);
DBAlliance aa = getAlliance();

try {
String response = request.get(20, TimeUnit.SECONDS);
String response = auth.withdrawResources(aa, receiver, ResourceType.resourcesToArray(transfer), note);
TransferResult category = categorize(receiver, transfer, note, response);
if (category.getStatus() == TransferStatus.SUCCESS || category.getStatus() == TransferStatus.SENT_TO_ALLIANCE_BANK) {
setLastSuccessfulTransfer(receiver, ResourceType.resourcesToArray(transfer));
}
return category;
} catch (InterruptedException | ExecutionException | TimeoutException e) {
} catch (Exception e) {
return new TransferResult(TransferStatus.OTHER, receiver, transfer, note).addMessage("Timeout: " + e.getMessage());
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import link.locutus.discord.apiv1.enums.ResourceType;
import link.locutus.discord.pnw.NationOrAlliance;
import link.locutus.discord.util.PW;
import link.locutus.discord.web.WebUtil;
import org.json.JSONObject;

import java.util.Map;
Expand All @@ -19,7 +20,7 @@ public class BankRequestHandler {

public Future<String> addRequest(UUID uuid, NationOrAlliance recipient, double[] amt, String note) {
// token
String txStr = ResourceType.resourcesToJson(recipient.getName(), recipient.isNation(), ResourceType.resourcesToMap(amt), note);
String txStr = WebUtil.GSON.toJson(ResourceType.resourcesToJson(recipient, ResourceType.resourcesToMap(amt), note));
JSONObject json = new JSONObject();
json.put("transfer", new JSONObject(txStr));
json.put("token", uuid.toString());
Expand Down
Loading

0 comments on commit b9e0875

Please sign in to comment.