AMP automation

This commit is contained in:
Seth 2020-08-07 22:51:09 -07:00
parent 075299dbd9
commit 2ecde80b5f
No known key found for this signature in database
GPG Key ID: A7BAB4E14F089CF3
15 changed files with 355 additions and 55 deletions

View File

@ -0,0 +1,187 @@
package me.totalfreedom.totalfreedommod;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import joptsimple.internal.Strings;
import lombok.Getter;
import me.totalfreedom.totalfreedommod.admin.Admin;
import me.totalfreedom.totalfreedommod.config.ConfigEntry;
import me.totalfreedom.totalfreedommod.rank.Rank;
import me.totalfreedom.totalfreedommod.util.FLog;
import me.totalfreedom.totalfreedommod.util.FUtil;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class AMP extends FreedomService
{
public String URL = ConfigEntry.AMP_URL.getString();
private String API_URL = URL + "/API/Core";
private String USERNAME = ConfigEntry.AMP_USERNAME.getString();
private String PASSWORD = ConfigEntry.AMP_PASSWORD.getString();
private String SESSION_ID;
@Getter
private boolean enabled = !Strings.isNullOrEmpty(URL);
private final List<String> headers = Arrays.asList("Accept:application/json");
public void onStart()
{
if (enabled)
{
login();
}
}
public void onStop()
{
if (enabled)
{
logout();
}
}
public void login()
{
JSONObject json = new JSONObject();
json.put("username", USERNAME);
json.put("password", PASSWORD);
json.put("token", "");
json.put("rememberMe", false);
String response;
try
{
response = FUtil.sendRequest(API_URL + "/Login", "POST", headers, json.toJSONString());
}
catch (IOException e)
{
e.printStackTrace();
return;
}
JSONObject jsonResponse;
try
{
jsonResponse = (JSONObject)new JSONParser().parse(response);
}
catch (ParseException e)
{
e.printStackTrace();
return;
}
Object sessionID = jsonResponse.get("sessionID");
if (sessionID == null)
{
FLog.warning("Invalid AMP credentials have been specified in the config");
enabled = false;
return;
}
SESSION_ID = sessionID.toString();
FLog.info("Logged into AMP");
}
public void logout()
{
JSONObject json = new JSONObject();
json.put("SESSIONID", SESSION_ID);
try
{
FUtil.sendRequest(API_URL + "/Logout", "POST", headers, json.toJSONString());
}
catch (IOException e)
{
e.printStackTrace();
return;
}
FLog.info("Logged out of AMP");
}
public void updateAccountStatus(Admin admin)
{
String username = admin.getAmpUsername();
if (username == null || !enabled)
{
return;
}
if (!admin.isActive() || admin.getRank() != Rank.SENIOR_ADMIN)
{
FLog.debug("Disabling amp acc");
setAccountEnabled(username, false);
return;
}
FLog.debug("Enabling amp acc");
setAccountEnabled(username, true);
}
public void createAccount(String username, String password)
{
makeAccount(username);
setPassword(username, password);
}
public void setAccountEnabled(String username, boolean enable)
{
JSONObject json = new JSONObject();
json.put("Username", username);
json.put("Disabled", !enable);
json.put("PasswordExpires", false);
json.put("CannotChangePassword", false);
json.put("MustChangePassword", false);
json.put("SESSIONID", SESSION_ID);
try
{
FUtil.sendRequest(API_URL + "/UpdateUserInfo", "POST", headers, json.toJSONString());
}
catch (IOException e)
{
e.printStackTrace();
return;
}
}
private void makeAccount(String username)
{
JSONObject json = new JSONObject();
json.put("Username", username);
json.put("SESSIONID", SESSION_ID);
try
{
FUtil.sendRequest(API_URL + "/CreateUser", "POST", headers, json.toJSONString());
}
catch (IOException e)
{
e.printStackTrace();
return;
}
}
public void setPassword(String username, String password)
{
JSONObject json = new JSONObject();
json.put("Username", username);
json.put("NewPassword", password);
json.put("SESSIONID", SESSION_ID);
try
{
FUtil.sendRequest(API_URL + "/ResetUserPassword", "POST", headers, json.toJSONString());
}
catch (IOException e)
{
e.printStackTrace();
return;
}
}
}

View File

@ -1,11 +1,10 @@
package me.totalfreedom.totalfreedommod.reddit;
package me.totalfreedom.totalfreedommod;
import com.google.common.base.Strings;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import me.totalfreedom.totalfreedommod.FreedomService;
import me.totalfreedom.totalfreedommod.config.ConfigEntry;
import me.totalfreedom.totalfreedommod.player.PlayerData;
import me.totalfreedom.totalfreedommod.rank.Displayable;
@ -126,7 +125,7 @@ public class Reddit extends FreedomService
public String addLinkCode(PlayerData data, String username)
{
String code = FUtil.randomString(10);
String code = FUtil.randomAlphanumericString(10);
linkCodes.put(code, data);
pending.put(data, username);
return code;

View File

@ -42,7 +42,6 @@ import me.totalfreedom.totalfreedommod.permissions.PermissionManager;
import me.totalfreedom.totalfreedommod.player.PlayerList;
import me.totalfreedom.totalfreedommod.punishments.PunishmentList;
import me.totalfreedom.totalfreedommod.rank.RankManager;
import me.totalfreedom.totalfreedommod.reddit.Reddit;
import me.totalfreedom.totalfreedommod.shop.Shop;
import me.totalfreedom.totalfreedommod.shop.Votifier;
import me.totalfreedom.totalfreedommod.sql.SQLite;
@ -139,6 +138,7 @@ public class TotalFreedomMod extends JavaPlugin
public EntityWiper ew;
public Sitter st;
public VanishBridge vb;
public AMP amp;
//public HubWorldRestrictions hwr;
//
@ -237,6 +237,7 @@ public class TotalFreedomMod extends JavaPlugin
ew = new EntityWiper();
st = new Sitter();
vb = new VanishBridge();
amp = new AMP();
// Single admin utils
cs = new CommandSpy();

View File

@ -1,8 +1,8 @@
package me.totalfreedom.totalfreedommod.admin;
import com.google.common.collect.Lists;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
@ -29,7 +29,7 @@ public class Admin
@Setter
private Rank rank = Rank.SUPER_ADMIN;
@Getter
private final List<String> ips = Lists.newArrayList();
private final List<String> ips = new ArrayList<>();
@Getter
@Setter
private Date lastLogin = new Date();
@ -50,7 +50,7 @@ public class Admin
private Boolean oldTags = false;
@Getter
@Setter
private Boolean logStick = false;
private String ampUsername = null;
public Admin(Player player)
{
@ -73,7 +73,7 @@ public class Admin
this.potionSpy = resultSet.getBoolean("potion_spy");
this.acFormat = resultSet.getString("ac_format");
this.oldTags = resultSet.getBoolean("old_tags");
this.logStick = resultSet.getBoolean("log_stick");
this.ampUsername = resultSet.getString("amp_username");
}
catch (SQLException e)
{
@ -95,18 +95,11 @@ public class Admin
.append("- Potion Spy: ").append(potionSpy).append("\n")
.append("- Admin Chat Format: ").append(acFormat).append("\n")
.append("- Old Tags: ").append(oldTags).append("\n")
.append("- Log Stick: ").append(logStick).append("\n");
.append("- AMP Username: ").append(ampUsername).append("\n");
return output.toString();
}
public void loadFrom(Player player)
{
name = player.getName();
ips.clear();
ips.add(FUtil.getIp(player));
}
public Map<String, Object> toSQLStorable()
{
Map<String, Object> map = new HashMap<String, Object>()
@ -121,16 +114,11 @@ public class Admin
put("potion_spy", potionSpy);
put("ac_format", acFormat);
put("old_tags", oldTags);
put("log_stick", logStick);
put("amp_username", ampUsername);
}};
return map;
}
public boolean isAtLeast(Rank pRank)
{
return rank.isAtLeast(pRank);
}
public boolean hasLoginMessage()
{
return loginMessage != null && !loginMessage.isEmpty();

View File

@ -0,0 +1,101 @@
package me.totalfreedom.totalfreedommod.command;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import me.totalfreedom.totalfreedommod.admin.Admin;
import me.totalfreedom.totalfreedommod.player.PlayerData;
import me.totalfreedom.totalfreedommod.rank.Rank;
import me.totalfreedom.totalfreedommod.util.FUtil;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@CommandPermissions(level = Rank.SENIOR_ADMIN, source = SourceType.ONLY_IN_GAME)
@CommandParameters(description = "Manage your AMP account", usage = "/<command> <create | resetpassword>")
public class Command_amp extends FreedomCommand
{
@Override
public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole)
{
if (!plugin.amp.isEnabled())
{
msg("AMP integration is currently disabled.", ChatColor.RED);
return true;
}
PlayerData playerData = getData(playerSender);
if (playerData.getDiscordID() == null)
{
msg("You must have a linked discord account.", ChatColor.RED);
return true;
}
if (args.length == 0)
{
return false;
}
if (args[0].equals("create"))
{
msg("Creating your AMP account...", ChatColor.GREEN);
Admin admin = getAdmin(playerSender);
if (admin.getAmpUsername() != null)
{
msg("You already have an AMP account.", ChatColor.RED);
return true;
}
String username = sender.getName();
String password = FUtil.randomString(30);
admin.setAmpUsername(username);
plugin.al.save(admin);
plugin.al.updateTables();
plugin.amp.createAccount(username, password);
plugin.dc.sendAMPInfo(playerData, username, password);
msg("Successfully created your AMP account. Check your DMs from " + plugin.dc.formatBotTag() + " on discord to get your credentials.", ChatColor.GREEN);
return true;
}
else if (args[0].equals("resetpassword"))
{
Admin admin = getAdmin(playerSender);
if (admin.getAmpUsername() == null)
{
msg("You do not have an AMP account.", ChatColor.RED);
return true;
}
msg("Resetting your password...", ChatColor.GREEN);
String username = admin.getAmpUsername();
String password = FUtil.randomString(30);
plugin.amp.setPassword(username,password);
plugin.dc.sendAMPInfo(playerData, username, password);
msg("Successfully reset your AMP account password. Check your DMs from " + plugin.dc.formatBotTag() + " on discord to get your credentials.", ChatColor.GREEN);
return true;
}
return false;
}
@Override
public List<String> getTabCompleteOptions(CommandSender sender, Command command, String alias, String[] args)
{
if (args.length == 1 && plugin.al.isSeniorAdmin(sender))
{
return Arrays.asList("create", "resetpassword");
}
return Collections.emptyList();
}
}

View File

@ -77,7 +77,7 @@ public class Command_donator extends FreedomCommand
try
{
FUtil.postRequestToEndpoint(url, "POST", headers, payload);
FUtil.sendRequest(url, "POST", headers, payload);
}
catch (IOException e)
{

View File

@ -51,6 +51,7 @@ public class Command_doom extends FreedomCommand
admin.setActive(false);
plugin.al.save(admin);
plugin.al.updateTables();
plugin.amp.updateAccountStatus(admin);
if (plugin.dc.enabled && ConfigEntry.DISCORD_ROLE_SYNC.getBoolean())
{
plugin.dc.syncRoles(admin, plugin.pl.getData(admin.getName()).getDiscordID());

View File

@ -204,14 +204,6 @@ public class Command_myadmin extends FreedomCommand
msg((target.getOldTags() ? "Enabled" : "Disabled") + " old tags.");
return true;
}
case "logstick":
{
target.setLogStick(!target.getLogStick());
plugin.al.save(target);
plugin.al.updateTables();
msg((target.getLogStick() ? "Enabled" : "Disabled") + " log-stick lookup.");
return true;
}
case "syncroles":
{
@ -262,7 +254,7 @@ public class Command_myadmin extends FreedomCommand
}
List<String> singleArguments = Arrays.asList("clearips", "setlogin", "setacformat");
List<String> doubleArguments = Arrays.asList("clearip", "clearlogin", "clearacformat", "oldtags", "logstick", "syncroles");
List<String> doubleArguments = Arrays.asList("clearip", "clearlogin", "clearacformat", "oldtags", "syncroles");
if (args.length == 1)
{
List<String> options = new ArrayList<>();

View File

@ -111,6 +111,8 @@ public class Command_saconfig extends FreedomCommand
plugin.dc.syncRoles(admin, plugin.pl.getData(admin.getName()).getDiscordID());
}
plugin.amp.updateAccountStatus(admin);
msg("Set " + admin.getName() + "'s rank to " + rank.getName());
return true;
}
@ -203,6 +205,7 @@ public class Command_saconfig extends FreedomCommand
plugin.al.addAdmin(admin);
plugin.rm.updateDisplay(player);
plugin.amp.updateAccountStatus(admin);
}
else // Existing admin
{
@ -239,6 +242,7 @@ public class Command_saconfig extends FreedomCommand
{
plugin.dc.syncRoles(admin, plugin.pl.getData(player).getDiscordID());
}
plugin.amp.updateAccountStatus(admin);
}
if (player != null)
@ -289,9 +293,11 @@ public class Command_saconfig extends FreedomCommand
if (plugin.dc.enabled && ConfigEntry.DISCORD_ROLE_SYNC.getBoolean())
{
plugin.dc.syncRoles(admin, plugin.pl.getData(player).getDiscordID());
plugin.dc.syncRoles(admin, plugin.pl.getData(admin.getName()).getDiscordID());
}
plugin.amp.updateAccountStatus(admin);
return true;
}

View File

@ -98,6 +98,10 @@ public enum ConfigEntry
REDDIT_EXECUTIVE_FLAIR_ID(String.class, "reddit.executive_flair_id"),
REDDIT_SERVER_OWNER_FLAIR_ID(String.class, "reddit.server_owner_flair_id"),
//
AMP_URL(String.class, "amp.url"),
AMP_USERNAME(String.class, "amp.username"),
AMP_PASSWORD(String.class, "amp.password"),
//
DONATION_PROBOARDS_URL(String.class, "donation.proboards_url"),
DONATION_GROUP_ID(String.class, "donation.donator_group_id"),
DONATION_SESSION_ID(String.class, "donation.session_id"),

View File

@ -1,6 +1,5 @@
package me.totalfreedom.totalfreedommod.discord;
import com.earth2me.essentials.User;
import com.google.common.base.Strings;
import java.io.File;
import java.io.FileWriter;
@ -21,6 +20,7 @@ import me.totalfreedom.totalfreedommod.config.ConfigEntry;
import me.totalfreedom.totalfreedommod.player.PlayerData;
import me.totalfreedom.totalfreedommod.rank.Rank;
import me.totalfreedom.totalfreedommod.util.FLog;
import me.totalfreedom.totalfreedommod.util.FUtil;
import net.dv8tion.jda.api.AccountType;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.JDA;
@ -33,6 +33,7 @@ import net.dv8tion.jda.api.entities.PrivateChannel;
import net.dv8tion.jda.api.entities.Role;
import net.dv8tion.jda.api.entities.SelfUser;
import net.dv8tion.jda.api.entities.TextChannel;
import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.events.ReadyEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import net.dv8tion.jda.internal.utils.concurrent.CountingThreadFactory;
@ -144,11 +145,19 @@ public class Discord extends FreedomService
}
}
public void sendAMPInfo(PlayerData playerData, String username, String password)
{
User user = bot.getUserById(playerData.getDiscordID());
String message = "The following is your AMP details:\n\nUsername: " + username + "\nPassword: " + password + "\n\nYou can connect to AMP at " + plugin.amp.URL;
PrivateChannel privateChannel = user.openPrivateChannel().complete();
privateChannel.sendMessage(message).complete();
}
public boolean sendBackupCodes(PlayerData playerData)
{
List<String> codes = generateBackupCodes();
List<String> encryptedCodes = generateEncryptedBackupCodes(codes);
net.dv8tion.jda.api.entities.User user = bot.getUserById(playerData.getDiscordID());
User user = bot.getUserById(playerData.getDiscordID());
File file = generateBackupCodesFile(playerData.getName(), codes);
if (file == null)
{
@ -167,22 +176,11 @@ public class Discord extends FreedomService
List<String> codes = new ArrayList<>();
for (int i = 0; i < 10; i++)
{
codes.add(randomString(10));
codes.add(FUtil.randomAlphanumericString(10));
}
return codes;
}
public String randomString(int size)
{
List<String> chars = Arrays.asList("ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890abcdefghijklmnopqrstuvwxyz".split("(?!^)"));
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < size; i++)
{
stringBuilder.append(chars.get(random.nextInt(chars.size())));
}
return stringBuilder.toString();
}
public String generateCode(int size)
{
String code = "";
@ -371,7 +369,7 @@ public class Discord extends FreedomService
String location = "World: " + reported.getLocation().getWorld().getName() + ", X: " + reported.getLocation().getBlockX() + ", Y: " + reported.getLocation().getBlockY() + ", Z: " + reported.getLocation().getBlockZ();
embedBuilder.addField("Location", location, true);
embedBuilder.addField("Game Mode", WordUtils.capitalizeFully(reported.getGameMode().name()), true);
User user = plugin.esb.getEssentialsUser(reported.getName());
com.earth2me.essentials.User user = plugin.esb.getEssentialsUser(reported.getName());
embedBuilder.addField("God Mode", WordUtils.capitalizeFully(String.valueOf(user.isGodModeEnabled())), true);
if (user.getNickname() != null)
{

View File

@ -74,7 +74,7 @@ public class Shop extends FreedomService
return;
}
reactionString = FUtil.randomString(ConfigEntry.SHOP_REACTIONS_STRING_LENGTH.getInteger());
reactionString = FUtil.randomAlphanumericString(ConfigEntry.SHOP_REACTIONS_STRING_LENGTH.getInteger());
FUtil.bcastMsg(prefix + ChatColor.AQUA + "Enter the code above to win " + ChatColor.GOLD + coinsPerReactionWin + ChatColor.AQUA + " coins!", false);

View File

@ -70,7 +70,7 @@ public class SQLite extends FreedomService
{
try
{
connection.createStatement().execute("CREATE TABLE `bans` ( `name` VARCHAR, `ips` VARCHAR, `by` VARCHAR NOT NULL, `at` LONG NOT NULL, `expires` LONG, `reason` VARCHAR );");
connection.createStatement().execute("CREATE TABLE `bans` (`name` VARCHAR, `ips` VARCHAR, `by` VARCHAR NOT NULL, `at` LONG NOT NULL, `expires` LONG, `reason` VARCHAR);");
}
catch (SQLException e)
{
@ -82,7 +82,7 @@ public class SQLite extends FreedomService
{
try
{
connection.createStatement().execute("CREATE TABLE `admins` (`username` VARCHAR NOT NULL, `ips` VARCHAR NOT NULL, `rank` VARCHAR NOT NULL, `active` BOOLEAN NOT NULL, `last_login` LONG NOT NULL, `login_message` VARCHAR, `command_spy` BOOLEAN NOT NULL, `potion_spy` BOOLEAN NOT NULL, `ac_format` VARCHAR, `old_tags` BOOLEAN NOT NULL, `log_stick` BOOLEAN NOT NULL);");
connection.createStatement().execute("CREATE TABLE `admins` (`username` VARCHAR NOT NULL, `ips` VARCHAR NOT NULL, `rank` VARCHAR NOT NULL, `active` BOOLEAN NOT NULL, `last_login` LONG NOT NULL, `login_message` VARCHAR, `command_spy` BOOLEAN NOT NULL, `potion_spy` BOOLEAN NOT NULL, `ac_format` VARCHAR, `old_tags` BOOLEAN NOT NULL, `amp_username` VARCHAR);");
}
catch (SQLException e)
{
@ -257,7 +257,7 @@ public class SQLite extends FreedomService
statement.setBoolean(8, admin.getPotionSpy());
statement.setString(9, admin.getAcFormat());
statement.setBoolean(10, admin.getOldTags());
statement.setBoolean(11, admin.getLogStick());
statement.setString(11, admin.getAmpUsername());
statement.executeUpdate();
}
catch (SQLException e)

View File

@ -223,7 +223,7 @@ public class FUtil
List<String> headers = new ArrayList<>();
headers.add("Accept:application/json");
headers.add("Content-Type:application/json");
String response = postRequestToEndpoint("https://api.mojang.com/profiles/minecraft", "POST", headers, json.toString());
String response = sendRequest("https://api.mojang.com/profiles/minecraft", "POST", headers, json.toString());
// Don't care how stupid this looks, couldn't find anything to parse a json string to something readable in java with something not horrendously huge, maybe im just retarded
Pattern pattern = Pattern.compile("(?<=\"id\":\")[a-f0-9].{31}");
Matcher matcher = pattern.matcher(response);
@ -240,7 +240,7 @@ public class FUtil
return null;
}
public static String postRequestToEndpoint(String endpoint, String method, List<String>headers, String body) throws IOException
public static String sendRequest(String endpoint, String method, List<String>headers, String body) throws IOException
{
URL url = new URL(endpoint);
HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
@ -639,12 +639,26 @@ public class FUtil
}
public static String randomString(int length)
{
String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvxyz0123456789-_=+[]{};:,.<>~";
String randomString = "";
for (int i = 0; i < length; i++)
{
int selectedCharacter = randomInteger(1, characters.length()) - 1;
randomString += characters.charAt(selectedCharacter);
}
return randomString;
}
public static String randomAlphanumericString(int length)
{
String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvxyz0123456789";
String randomString = "";
for (int i = 0; i < length; i++)
{
int selectedCharacter = randomInteger(1, characters.length()) - 1;
randomString += characters.charAt(selectedCharacter);

View File

@ -114,6 +114,15 @@ reddit:
executive_flair_id: ''
# Owner flair ID
server_owner_flair_id: ''
# AMP
amp:
# URL - do not leave a trailing forward slash
url: ''
# Username
username: ''
# Password
password: ''
# The shop
shop: