Skip to content

Commit

Permalink
Spy tracker debug legacy setting
Browse files Browse the repository at this point in the history
  • Loading branch information
xdnw committed Sep 3, 2024
1 parent 9374c01 commit 8300f22
Show file tree
Hide file tree
Showing 11 changed files with 102 additions and 67 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -95,11 +95,11 @@ public String read(PagePriority priority, QueryURLV2 url, String arg, String que
String successStr = "success\":";
int successIndex = json.indexOf(successStr);
if (successIndex == -1) {
throw new IOException("Invalid response: " + json + " for " + url.getUrl("XXXX", arg, query));
throw new IOException("Invalid response: " + StringMan.stripApiKey(json) + " for " + url.getUrl("XXXX", arg, query));
}
char tf = json.charAt(successIndex + successStr.length());
if (tf != 't') {
throw new IOException("Failed: " + json + " for " + url.getUrl("XXXX", arg, query));
throw new IOException("Failed: " + StringMan.stripApiKey(json) + " for " + url.getUrl("XXXX", arg, query));
}

String startStr = "\"data\":";
Expand Down
42 changes: 32 additions & 10 deletions src/main/java/link/locutus/discord/apiv3/PoliticsAndWarV3.java
Original file line number Diff line number Diff line change
Expand Up @@ -131,20 +131,23 @@ public enum ErrorResponse {
}

private static class RateLimit {
// Amount of requests allowed per interval
public volatile int limit;
// The interval in milliseconds (typically 60_000)
public volatile int intervalMs;
public volatile long resetAfterMs;
// The number of ms until the ratelimit resets (unused)
public volatile long resetAfterMs_unused;
// The remaining number of requests this interval
public volatile int remaining;
// the unix epoch time in milliseconds when the ratelimit resets
public volatile long resetMs;

public void reset(long now) {
if (now > resetMs) {
remaining = limit;

long remainder = (now - resetMs) % intervalMs;

resetAfterMs = intervalMs - remainder;
resetMs = now + resetAfterMs;
resetAfterMs_unused = intervalMs - remainder;
resetMs = now + resetAfterMs_unused;
}
}
}
Expand All @@ -171,7 +174,9 @@ public <T extends Serializable> List<T> readSnapshot(PagePriority priority, Clas
JsonObject obj = JsonParser.parseString(body).getAsJsonObject();
String errorRaw = obj.get("error").getAsString();
if (errorRaw.equalsIgnoreCase("rate-limited")) {
Thread.sleep(30500);
long amt = 30_500;
setRateLimit(amt);
Thread.sleep(amt);
continue;
} else {
errorMsg = errorRaw;
Expand All @@ -189,7 +194,23 @@ public <T extends Serializable> List<T> readSnapshot(PagePriority priority, Clas
if (body != null && !errorMsg.contains("rate-limited") && !errorMsg.contains("database error") && !errorMsg.contains("couldn't find api key")) {
Logg.text("Unknown error with APIv3 Snapshot response: " + errorMsg + "\n\n---START BODY\n\n" + body + "\n\n---END BODY---\n\n");
}
rethrow(new IllegalArgumentException(errorMsg.replace(pair.getKey(), "XXX")), pair, true);
rethrow(new IllegalArgumentException(StringUtils.replaceIgnoreCase(errorMsg, pair.getKey(), "XXX")), pair, true);
}
}

private void setRateLimit(long timeMs) {
synchronized (rateLimitGlobal) {
if (rateLimitGlobal.intervalMs == 0) {
rateLimitGlobal.intervalMs = 60_000;
}
if (rateLimitGlobal.limit == 0) {
rateLimitGlobal.limit = 60;
}
long now = System.currentTimeMillis();
rateLimitGlobal.resetAfterMs_unused = timeMs;
rateLimitGlobal.remaining = 0;
rateLimitGlobal.resetMs = now + timeMs;
rateLimitGlobal.limit = 0;
}
}

Expand All @@ -211,8 +232,9 @@ private void handleRateLimit() {
throw new RuntimeException(e);
}
}
now = System.currentTimeMillis();
}
rateLimitGlobal.reset(System.currentTimeMillis());
rateLimitGlobal.reset(now);
rateLimitGlobal.remaining--;
}
}
Expand Down Expand Up @@ -270,7 +292,7 @@ public <T> T readTemplate(PagePriority priority, boolean pagination, GraphQLRequ
}
String message = errorMessages.isEmpty() ? errors.toString() : StringMan.join(errorMessages, "\n");
message = StringMan.stripApiKey(message);
rethrow(new IllegalArgumentException(message.replace(pair.getKey(), "XXX")), pair, true);
rethrow(new IllegalArgumentException(StringUtils.replaceIgnoreCase(message, pair.getKey(), "XXX")), pair, true);
}

result = jacksonObjectMapper.readValue(body, resultBody);
Expand Down Expand Up @@ -338,7 +360,7 @@ public <T> T readTemplate(PagePriority priority, boolean pagination, GraphQLRequ
HttpHeaders header = exchange.getHeaders();
synchronized (rateLimitGlobal) {
if (header.containsKey("X-RateLimit-Reset-After")) {
rateLimitGlobal.resetAfterMs = Long.parseLong(Objects.requireNonNull(header.get("X-RateLimit-Reset-After")).get(0)) * 1000L;
rateLimitGlobal.resetAfterMs_unused = Long.parseLong(Objects.requireNonNull(header.get("X-RateLimit-Reset-After")).get(0)) * 1000L;
}
if (header.containsKey("X-RateLimit-Limit")) {
rateLimitGlobal.limit = Integer.parseInt(Objects.requireNonNull(header.get("X-RateLimit-Limit")).get(0));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import link.locutus.discord.util.FileUtil;
import link.locutus.discord.util.StringMan;
import link.locutus.discord.util.io.PagePriority;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import java.io.IOException;
Expand Down Expand Up @@ -233,7 +234,7 @@ private String getChannel() {
return channel.getAsString();
}
}
String msg = channelInfo.replace(pnwKey, "XXX");
String msg = StringUtils.replaceIgnoreCase(channelInfo, pnwKey, "XXX");
msg = msg.replaceAll("(?i)[\\[\\]\"\\n^:\\s,\\.](?=.*[A-Za-z])(?=.*\\d)[0-9A-F]{14,}(?=[\\[\\]\"\\n$:\\s,\\.]|$)", "XXX");
throw new PnwPusherError(msg);
} catch (IOException e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@
import net.dv8tion.jda.api.entities.channel.concrete.Category;
import net.dv8tion.jda.api.entities.channel.middleman.GuildChannel;
import net.dv8tion.jda.api.entities.channel.middleman.MessageChannel;
import org.apache.commons.lang3.StringUtils;

import java.nio.ByteBuffer;
import java.util.*;
Expand Down Expand Up @@ -359,7 +360,7 @@ public boolean run(Guild guild, IMessageIO channel, final User msgUser, String c
// return;
}
if (result != null && !result.isEmpty()) {
result = result.replaceAll("(?i)" + Locutus.loader().getApiKey(), "XXX");
result = StringUtils.replaceIgnoreCase(result, Locutus.loader().getApiKey(), "XXX");
// result = result.replaceAll("(?i)(?<=^|[^A-Fa-f0-9])(?:[0-9a-f]{2}){7,}(?=[^A-Fa-f0-9]|$)", "XXX");
channel.send(result);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.PARAMETER, ElementType.METHOD})
public @interface Arg {
String[] requiresAny() default {};
String[] requiresAll() default {};
String[] requiresNone() default {};

String value();
int group() default -1;
String[] aliases() default {};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,6 @@
import java.util.function.Supplier;

public class SlashCommandManager extends ListenerAdapter {
public static boolean PRINT_MISSING = false;

private static final Map<Type, Collection<ChannelType>> CHANNEL_TYPES = new ConcurrentHashMap<>();
private static final Map<Type, OptionType> OPTION_TYPES = new ConcurrentHashMap<>();

Expand Down Expand Up @@ -578,7 +576,7 @@ private List<OptionData> createOptions(ParametricCallable cmd, List<UpdateComman
if (parser != null && !parser.getKey().equals(emptyKey)) {
option.setAutoComplete(true);
} else {
if (bindingKeys.add(completerKey) && PRINT_MISSING) {
if (bindingKeys.add(completerKey) && Settings.INSTANCE.LEGACY_SETTINGS.PRINT_MISSING_AUTOCOMPLETE) {
Logg.text("No autocomplete binding: " + binding.getKey());
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,9 @@

public class ConflictCommands {
@Command(desc = "View a conflict's configured information")
public String info(ConflictManager manager, Conflict conflict, boolean showParticipants, @Switch("d") boolean hideDeleted) {
public String info(ConflictManager manager, Conflict conflict, boolean showParticipants,
@Switch("d") boolean hideDeleted,
@Switch("i") boolean showIds) {
if (hideDeleted && !showParticipants) {
throw new IllegalArgumentException("Cannot hide deleted conflicts without `showParticipants:True`");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,7 @@
import org.json.JSONObject;

import java.io.IOException;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

Expand Down Expand Up @@ -128,8 +125,19 @@ public String optOut(@Me User user, DiscordDB db, @Default("true") boolean optOu
return "Set " + DiscordMeta.OPT_OUT + " to " + optOut;
}

public static String handleOptOut(Member member, GuildDB db, Roles lcRole, Boolean forceOptOut) {
public static String handleOptOut(Member member, GuildDB db, Roles lcRole, Boolean forceOptOut, Roles... optInRoles) {
Guild guild = db.getGuild();
List<Role> optInDiscRoles = new ArrayList<>();
for (Roles r : optInRoles) {
Role discR = r.toRole(guild);
if (discR != null) {
optInDiscRoles.add(discR);
}
}
List<String> notes = new ArrayList<>();
if (optInDiscRoles.isEmpty() && optInRoles.length > 0) {
notes.add("No role `" + Arrays.stream(optInRoles).map(Roles::name).collect(Collectors.joining("`, `")) + "` is set. Have an admin use e.g. " + CM.role.setAlias.cmd.locutusRole(optInRoles[0].name()).discordRole("@someRole"));
}
Role role = lcRole.toRole(guild);
if (role == null) {
// find role by name
Expand All @@ -142,14 +150,27 @@ public static String handleOptOut(Member member, GuildDB db, Roles lcRole, Boole
db.addRole(lcRole, role, 0);
}
}
if (member.getRoles().contains(role)) {

List<Role> memberRoles = member.getRoles();
boolean hasAnyOptIn = optInDiscRoles.stream().anyMatch(memberRoles::contains);
if (memberRoles.contains(role)) {
if (forceOptOut == Boolean.TRUE) {
return "You are already opted out of " + lcRole.name() + " alerts";
}
RateLimitUtil.complete(guild.removeRoleFromMember(member, role));
return "Opted back in to " + lcRole.name() + " alerts (@" + role.getName() + " removed from your user). Use the command again to opt out";
String msg;
if (!optInDiscRoles.isEmpty() && !hasAnyOptIn) {
msg = "Your opt out role has been removed (@" + role.getName() + " removed) however you lack a role required to opt back in (@" + Arrays.stream(optInRoles).map(Roles::name).collect(Collectors.joining(", @")) + ")";
} else {
msg = "Opted back in to " + lcRole.name() + " alerts (@" + role.getName() + " removed)";
}
msg += ". Use the command again to opt out";
return msg;
}
if (forceOptOut == Boolean.FALSE) {
if (!optInDiscRoles.isEmpty() && !hasAnyOptIn) {
return "You do not have the opt out role (@" + role.getName() + ") however lack a role to opt in (@" + Arrays.stream(optInRoles).map(Roles::name).collect(Collectors.joining(", @")) + ")";
}
return "You are already opted in to " + lcRole.name() + " alerts";
}
RateLimitUtil.complete(guild.addRoleToMember(member, role));
Expand All @@ -164,12 +185,12 @@ public String auditAlertOptOut(@Me Member member, @Me DBNation me, @Me Guild gui

@Command(desc = "Toggle your opt out of enemy alerts")
public String enemyAlertOptOut(@Me GuildDB db, @Me User user, @Me Member member, @Me Guild guild) {
return PlayerSettingCommands.handleOptOut(member, db, Roles.WAR_ALERT_OPT_OUT, null);
return PlayerSettingCommands.handleOptOut(member, db, Roles.WAR_ALERT_OPT_OUT, null, Roles.ENEMY_ALERT_OFFLINE, Roles.BEIGE_ALERT);
}

@Command(desc = "Toggle your opt out of bounty alerts")
public String bountyAlertOptOut(@Me GuildDB db, @Me User user, @Me Member member, @Me Guild guild) {
return PlayerSettingCommands.handleOptOut(member, db, Roles.BOUNTY_ALERT_OPT_OUT, null);
return PlayerSettingCommands.handleOptOut(member, db, Roles.BOUNTY_ALERT_OPT_OUT, null, Roles.BOUNTY_ALERT);
}

@Command(desc = "Set the required transfer market value required for automatic bank alerts\n" +
Expand Down
38 changes: 12 additions & 26 deletions src/main/java/link/locutus/discord/config/Settings.java
Original file line number Diff line number Diff line change
Expand Up @@ -343,37 +343,11 @@ public static class PROXY {
}

public static class LEGACY_SETTINGS {
@Final
@Ignore
@Comment("Open browser window when these ppl do attacks")
public List<Integer> ATTACKER_DESKTOP_ALERTS = new ArrayList<>();

@Final
@Ignore
@Comment("Timestamp for when marked deposits were introduced")
public long MARKED_DEPOSITS_DATE = 1622661922L * 1000L;

@Final
@Ignore
public boolean OPEN_DESKTOP_FOR_CAPTCHA = false;

@Final
@Ignore
public boolean OPEN_DESKTOP_FOR_MISTRADES = false;

@Final
@Ignore
public boolean OPEN_DESKTOP_FOR_RAIDS = false;

@Final
@Ignore
@Deprecated
@Comment("Access key for P&W (deprecated)")
public String ACCESS_KEY = "";
@Final
@Ignore // disabled (not super accurate and not fair)
@Deprecated
public boolean DEANONYMIZE_SPYOPS = false;
@Final
@Ignore // disabled (not super accurate and not fair)
@Deprecated
Expand All @@ -390,6 +364,18 @@ public static class LEGACY_SETTINGS {
@Deprecated
@Comment("Reduce the appearance of these always online nations for espionage alerts (if causing false positives)")
public List<Integer> ESPIONAGE_ALWAYS_ONLINE_AA = Arrays.asList();

@Ignore
@Final
@Comment("Print the binding types which lack an autocomplete\n" +
"Disabled by default, as its normal for some types not to have completion")
public boolean PRINT_MISSING_AUTOCOMPLETE = false;

@Ignore
@Final
@Comment("Print the espionage debug information\n" +
"Disabled by default, as it is verbose")
public boolean PRINT_ESPIONAGE_DEBUG = false;
}


Expand Down
1 change: 0 additions & 1 deletion src/main/java/link/locutus/discord/util/AlertUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,6 @@ public static void auditAlert(DBNation nation, AutoAuditType type, Function<Guil
if (optOut != null && optOut.contains(type)) return;
}

// TODO put result in database
Role pingOptOut = Roles.AUDIT_ALERT_OPT_OUT.toRole(channel.getGuild());
Role pingOptOut2 = Roles.AUDIT_ALERT_OPT_OUT.toRole(guild);
boolean hasOptOut = (pingOptOut != null && member.getRoles().contains(pingOptOut)) || (pingOptOut2 != null && member.getRoles().contains(pingOptOut2));
Expand Down
Loading

0 comments on commit 8300f22

Please sign in to comment.