Skip to content

Commit

Permalink
minor fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
xdnw committed Aug 5, 2023
1 parent fdc26ac commit 3749a31
Show file tree
Hide file tree
Showing 10 changed files with 201 additions and 89 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public void load(WarAttack attack) {
super.load(attack);
this.attcas1 = attack.getAtt_aircraft_lost();
this.defcas1 = attack.getDef_aircraft_lost();
this.defcas2 = attack.getDef_tanks_lost();
this.defcas2 = attack.getDef_soldiers_lost();
}

private static final MilitaryUnit[] UNITS = {MilitaryUnit.AIRCRAFT, MilitaryUnit.SOLDIER};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class IACommands {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@
import org.json.JSONObject;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.security.GeneralSecurityException;
import java.util.*;
import java.util.concurrent.CompletableFuture;
Expand Down Expand Up @@ -110,10 +111,12 @@ public void freeSpyOpsSheet(
@Arg("Number of spies required")
@Switch("s") Integer requireSpies,
@Switch("sheet") SpreadSheet sheet) throws GeneralSecurityException, IOException {
if (nations == null) nations = new SimpleNationList(db.getAllianceList().getNations());

List<DBNation> invalidNations = new ArrayList<>();
AllianceList aaList = db.getAllianceList();
Set<DBNation> aaNations = aaList.getNations(f -> f.getPositionEnum().id >= Rank.APPLICANT.id && f.getVm_turns() == 0 && nations.contains(f));
NationList finalNations = nations;
Set<DBNation> aaNations = aaList.getNations(f -> f.getPositionEnum().id >= Rank.APPLICANT.id && f.getVm_turns() == 0 && finalNations.contains(f));
if (aaNations.isEmpty()) {
throw new IllegalArgumentException("No nations in alliances " + StringMan.getString(aaList.getIds()) + " matched `nations` (vacation mode or applicants are ignored)");
}
Expand All @@ -131,7 +134,9 @@ public void freeSpyOpsSheet(
"{score}",
"{cities}",
"{spies}",
"{free_spy_ops}"
"{free_spy_ops}",
"{days_since_op}",
"{ops_alltime}"
)
);
if (addColumns != null) columns.addAll(addColumns);
Expand All @@ -154,17 +159,39 @@ public void freeSpyOpsSheet(
if (requireXFreeOps != null && free < requireXFreeOps) continue;
if (requireSpies != null && nation.getSpies() < requireSpies) continue;

locals.addProvider(Key.of(DBNation.class, Me.class), nation);
locals.addProvider(Key.of(User.class, Me.class), nation.getUser());
for (int i = 0; i < columns.size(); i++) {
String arg = columns.get(i);
arg = arg.replace("{free_spy_ops}", String.valueOf(free));
arg = arg.replace("{used_spy_ops}", String.valueOf(usedSlots));
String formatted = placeholders.format(locals, arg);

header.set(i, formatted);
int opsAllTime = 0;
long daysSinceOp = 0;
ByteBuffer allTimeBuf = nation.getMeta(NationMeta.SPY_OPS_AMOUNT_TOTAL);
if (allTimeBuf != null) {
opsAllTime = allTimeBuf.getInt();
}
long currentDay = TimeUtil.getDay();
ByteBuffer dayLastOpBuf = nation.getMeta(NationMeta.SPY_OPS_DAY);
if (dayLastOpBuf != null) {
long dayLastOp = dayLastOpBuf.getLong();
daysSinceOp = currentDay - dayLastOp;
}

header.set(0, "=HYPERLINK(\"politicsandwar.com/nation/id={nation_id}\", \"{nation}\")"
.replace("{nation_id}", nation.getId() + "")
.replace("{nation}", nation.getName()));

header.set(1, "=HYPERLINK(\"politicsandwar.com/alliance/id={alliance_id}\", \"{alliancename}\")"
.replace("{alliance_id}", nation.getAlliance_id() + "")
.replace("{alliancename}", nation.getAllianceName()));

header.set(2, nation.getScore() + "");

header.set(3, nation.getCities() + "");

header.set(4, nation.getSpies() + "");

header.set(5, free + "");

header.set(6, daysSinceOp + "");

header.set(7, opsAllTime + "");

sheet.addRow(new ArrayList<>(header));
}

Expand Down Expand Up @@ -751,10 +778,21 @@ public String revenue(@Me GuildDB db, @Me Guild guild, @Me IMessageIO channel, @
@Switch("t") boolean includeUntaxable,
@Arg("Exclude the new nation bonus")
@Switch("b") boolean excludeNationBonus) throws Exception {
if (nations.getNations().size() == 1) includeUntaxable = true;

ArrayList<DBNation> filtered = new ArrayList<>(nations.getNations());
int removed = 0;
if (!includeUntaxable) {
int size = filtered.size();
filtered.removeIf(f -> f.getAlliance_id() == 0 || f.getVm_turns() != 0);
filtered.removeIf(f -> f.isGray() || f.isBeige() || f.getPosition() <= 1);
removed = size - filtered.size();
}
if (filtered.size() == 0) {
if (removed > 0) {
throw new IllegalArgumentException("No nations to tax, all " + removed + " nations are untaxable. Use `includeUntaxable` to include them");
}
throw new IllegalArgumentException("No nations provided");
}
double[] cityProfit = new double[ResourceType.values.length];
double[] milUp = new double[ResourceType.values.length];
Expand Down Expand Up @@ -788,6 +826,11 @@ public String revenue(@Me GuildDB db, @Me Guild guild, @Me IMessageIO channel, @
} else {
response.append("\n`warn: Revenue is not sustainable`");
}

if (removed > 0) {
response.append("\n`warn: " + removed + " untaxable nations removed. Use 'includeUntaxable: True' to include them.`");
}

response.send();
return null;
}
Expand Down Expand Up @@ -1166,41 +1209,60 @@ public String copyPasta(@Me IMessageIO io, @Me GuildDB db, @Me Guild guild, @Me
if (!noRoles.isEmpty()) {
throw new IllegalArgumentException("You do not have the required roles to use this command: `" + StringMan.join(noRoles, ",") + "`");
}
} else if (!Roles.INTERNAL_AFFAIRS.has(author, guild)) {
return "Missing role: " + Roles.INTERNAL_AFFAIRS;
}

String value = db.getCopyPasta(key, true);
String value = db.getCopyPasta(key, true);

Set<String> missingRoles = null;
if (value == null) {
Map<String, String> map = db.getCopyPastas(member);
for (Map.Entry<String, String> entry : map.entrySet()) {
String otherKey = entry.getKey();
String[] split = otherKey.split("\\.");
if (!split[split.length - 1].equalsIgnoreCase(key)) continue;
Set<String> missingRoles = null;
if (value == null) {
Map<String, String> map = db.getCopyPastas(member);
for (Map.Entry<String, String> entry : map.entrySet()) {
String otherKey = entry.getKey();
String[] split = otherKey.split("\\.");
if (!split[split.length - 1].equalsIgnoreCase(key)) continue;

Set<String> localMissing = db.getMissingCopypastaPerms(otherKey, guild.getMember(author));
Set<String> localMissing = db.getMissingCopypastaPerms(otherKey, guild.getMember(author));

if (!localMissing.isEmpty()) {
missingRoles = localMissing;
continue;
}
if (!localMissing.isEmpty()) {
missingRoles = localMissing;
continue;
}

value = entry.getValue();
missingRoles = null;
value = entry.getValue();
missingRoles = null;
}
} else {
missingRoles = db.getMissingCopypastaPerms(key, guild.getMember(author));
}
} else {
missingRoles = db.getMissingCopypastaPerms(key, guild.getMember(author));
if (missingRoles != null && !missingRoles.isEmpty()) {
throw new IllegalArgumentException("You do not have the required roles to use this command: `" + StringMan.join(missingRoles, ",") + "`");
}
if (value == null) return "No message set for `" + key + "`. Plase use " + CM.copyPasta.cmd.toSlashMention() + "";

value = placeholders.format(store, value);

return value;
} else if (!Roles.INTERNAL_AFFAIRS.has(author, guild)) {
return "Missing role: " + Roles.INTERNAL_AFFAIRS;
}
if (missingRoles != null && !missingRoles.isEmpty()) {
throw new IllegalArgumentException("You do not have the required roles to use this command: `" + StringMan.join(missingRoles, ",") + "`");

if (!Roles.INTERNAL_AFFAIRS.has(author, guild)) return "No permission.";

String setKey = key;
if (requiredRolesAny != null && !requiredRolesAny.isEmpty()) {
setKey = requiredRolesAny.stream().map(Role::getId).collect(Collectors.joining(".")) + "." + key;
}

if (message.isEmpty() || message.equalsIgnoreCase("null")) {
db.deleteCopyPasta(key);
db.deleteCopyPasta(setKey);
return "Deleted message for `" + Settings.commandPrefix(true) + "copypasta " + key + "`";
} else {
db.setCopyPasta(setKey, message);
return "Added message for `" + Settings.commandPrefix(true) + "copypasta " + setKey + "`\n" +
"Remove using `" + Settings.commandPrefix(true) + "copypasta " + setKey + " null`";
}
if (value == null) return "No message set for `" + key + "`. Plase use " + CM.copyPasta.cmd.toSlashMention() + "";

value = placeholders.format(store, value);

return value;
}

@Command(desc = "Generate an audit report of a list of nations")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import link.locutus.discord.Locutus;
import link.locutus.discord.apiv1.core.ApiKeyPool;
import link.locutus.discord.apiv1.enums.AttackType;
import link.locutus.discord.apiv1.enums.SuccessType;
import link.locutus.discord.commands.manager.v2.command.CommandBehavior;
import link.locutus.discord.commands.manager.v2.command.IMessageBuilder;
Expand Down Expand Up @@ -236,6 +237,9 @@ public static boolean isActive(DBNation nation) {
}

public void update(AbstractCursor attack) {
if (attack.getAttack_type() == AttackType.PEACE) {
return;
}
int attackerId = attack.getAttacker_id();
int defenderId = attack.getDefender_id();
WarRoom roomTmp = warRoomMap.get(attackerId);
Expand Down Expand Up @@ -343,7 +347,7 @@ public void update(AbstractCursor attack) {
}
if (showInfra && attack.getInfra_destroyed() != 0) {
double worth = PnwUtil.calculateInfra(attack.getCity_infra_before() - attack.getInfra_destroyed(), attack.getCity_infra_before());
message += ". " + attack.getInfra_destroyed() + " infra worth $" + MathMan.format(worth) + " was destroyed";
message += ". " + MathMan.format(attack.getInfra_destroyed()) + " infra worth $" + MathMan.format(worth) + " was destroyed";
}
if (showCasualties) {
Map<MilitaryUnit, Integer> attLosses = attack.getUnitLosses(true);
Expand Down Expand Up @@ -682,7 +686,7 @@ public IMessageBuilder updatePin(boolean update) {
body.append(target.toMarkdown(true, true, false, false, true, false));
body.append("\n");

List<DBWar> wars = Locutus.imp().getWarDb().getWarsByNation(target.getNation_id(), WarStatus.ACTIVE, WarStatus.ATTACKER_OFFERED_PEACE, WarStatus.DEFENDER_OFFERED_PEACE);
List<DBWar> wars = target.getActiveWars();
for (DBWar war : wars) {
boolean defensive = war.attacker_id == target.getNation_id();
DBNation participant = Locutus.imp().getNationDB().getNation(war.attacker_id == target.getNation_id() ? war.defender_id : war.attacker_id);
Expand Down
15 changes: 12 additions & 3 deletions src/main/java/link/locutus/discord/db/NationDB.java
Original file line number Diff line number Diff line change
Expand Up @@ -765,6 +765,7 @@ public Set<Integer> updateRecentNations(Consumer<Event> eventConsumer) {
public List<Integer> getMostActiveNationIds(int amt) {
List<Map.Entry<Integer, Long>> nationIdActive = new ArrayList<>();

long turn = TimeUtil.getTurn();
Set<Integer> visited = new HashSet<>();
for (int i = 0; i < amt && !dirtyNations.isEmpty(); i++) {
try {
Expand All @@ -777,13 +778,16 @@ public List<Integer> getMostActiveNationIds(int amt) {
} catch (NoSuchElementException ignore) {}
}

long now = System.currentTimeMillis();
if (nationIdActive.size() < amt) {
synchronized (nationsById) {
for (DBNation nation : nationsById.values()) {
if (nation.getVm_turns() > 0) continue;
if (nation.getLeaving_vm() > turn) continue;

long lastFetched = nation.getLastFetchedUnitsMs();
long active = nation.lastActiveMs();
nationIdActive.add(Map.entry(nation.getNation_id(), active));
long diff = Math.max(active - lastFetched, 0) + Math.max(now - lastFetched, 0);
nationIdActive.add(Map.entry(nation.getNation_id(), diff));
}
}
}
Expand Down Expand Up @@ -824,7 +828,7 @@ public void updateDirtyNations(Consumer<Event> eventConsumer) {
ids = new ArrayList<>(dirtyNations);
dirtyNations.clear();
}
System.out.println("Ids " + ids.size());
System.out.println("Dirty nation Ids " + ids.size());
updateNations(ids, eventConsumer);
}

Expand Down Expand Up @@ -1764,13 +1768,18 @@ public Set<Integer> updateAllNations(Consumer<Event> eventConsumer) {
}

public void markDirtyIncorrectNations(boolean score, boolean cities) {
int originalSize = dirtyNations.size();
for (DBNation nation : getNationsMatching(f -> f.getVm_turns() == 0)) {
if (score && Math.round(100 * (nation.estimateScore() - nation.getScore())) > 0.01) {
dirtyNations.add(nation.getNation_id());
} else if (cities && nation.getCities() != getCitiesV3(nation.getNation_id()).size()) {
dirtyNations.add(nation.getNation_id());
}
}
int added = dirtyNations.size() - originalSize;
if (added > 10) {
System.out.println("Added " + added + " nations to dirty list");
}
}

public Set<Integer> updateNations(Collection<Nation> nations, Consumer<Event> eventConsumer) {
Expand Down
28 changes: 16 additions & 12 deletions src/main/java/link/locutus/discord/db/WarDB.java
Original file line number Diff line number Diff line change
Expand Up @@ -1448,12 +1448,14 @@ public boolean updateWarsSince(Consumer<Event> eventConsumer, long date) {
if (war.getNation(true) != null && war.getNation(false) != null) {
notDeleted++;
}
DBWar copy = eventConsumer != null ? new DBWar(war) : null;
war.status = WarStatus.EXPIRED;
activeWars.makeWarInactive(war);
warsToSave.add(war);
if (eventConsumer != null) {
warsToProcess.add(new AbstractMap.SimpleEntry<>(copy, war));
if (war.status != WarStatus.EXPIRED && war.isActive()) {
DBWar copy = eventConsumer != null ? new DBWar(war) : null;
war.status = WarStatus.EXPIRED;
activeWars.makeWarInactive(war);
warsToSave.add(war);
if (eventConsumer != null) {
warsToProcess.add(new AbstractMap.SimpleEntry<>(copy, war));
}
}
}

Expand Down Expand Up @@ -1583,12 +1585,14 @@ public boolean updateActiveWars2(Consumer<Event> eventConsumer) throws IOExcepti
if (war.getNation(true) != null && war.getNation(false) != null) {
notDeleted++;
}
DBWar copy = eventConsumer != null ? new DBWar(war) : null;
war.status = WarStatus.EXPIRED;
activeWars.makeWarInactive(war);
warsToSave.add(war);
if (eventConsumer != null) {
warsToProcess.add(new AbstractMap.SimpleEntry<>(copy, war));
if (war.status != WarStatus.EXPIRED && war.isActive()) {
DBWar copy = eventConsumer != null ? new DBWar(war) : null;
war.status = WarStatus.EXPIRED;
activeWars.makeWarInactive(war);
warsToSave.add(war);
if (eventConsumer != null) {
warsToProcess.add(new AbstractMap.SimpleEntry<>(copy, war));
}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1333,7 +1333,10 @@ public void accept(NationResponseProjection proj) {
if (nation.getEspionage_available() != (dbNation.isEspionageAvailable())) {
dbNation.setEspionageFull(!nation.getEspionage_available());
}
ops.put(dbNation, nation.getSpy_attacks());
if (nation.getSpy_attacks() != null) {
nation.setSpy_attacks(nation.getSpy_attacks());
ops.put(dbNation, nation.getSpy_attacks());
}
}
return ops;
}
Expand Down
Loading

0 comments on commit 3749a31

Please sign in to comment.