Skip to content

Commit

Permalink
Adapt to breaking API changes, catch TS3CommandFailedException's
Browse files Browse the repository at this point in the history
Always checkIfEnabled() for tasks before executing
Use Command::addCooldown instead of HalfClient::addCooldown
  • Loading branch information
Kakifrucht committed May 7, 2017
1 parent fbbc076 commit 9dee697
Show file tree
Hide file tree
Showing 11 changed files with 140 additions and 128 deletions.
2 changes: 1 addition & 1 deletion pom.xml
Expand Up @@ -7,7 +7,7 @@
<groupId>de.halfminer</groupId>
<artifactId>HalfminerBot</artifactId>
<name>Halfminer Bot</name>
<version>1.2.1</version>
<version>1.2.2</version>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
Expand Down
6 changes: 4 additions & 2 deletions src/main/java/de/halfminer/hmbot/BotListeners.java
Expand Up @@ -3,6 +3,7 @@
import com.github.theholywaffle.teamspeak3.TS3Api;
import com.github.theholywaffle.teamspeak3.api.TextMessageTargetMode;
import com.github.theholywaffle.teamspeak3.api.event.*;
import com.github.theholywaffle.teamspeak3.api.exception.TS3CommandFailedException;
import com.github.theholywaffle.teamspeak3.api.wrapper.ClientInfo;
import com.github.theholywaffle.teamspeak3.api.wrapper.ServerQueryInfo;
import de.halfminer.hmbot.cmd.CommandDispatcher;
Expand Down Expand Up @@ -71,8 +72,9 @@ public void onClientMoved(ClientMovedEvent e) {
if (this.channelOfBot == e.getTargetChannelId()) {
clientEnterMessageAndMove(e.getClientId());
} else if (e.getClientId() == idOfBot && e.getTargetChannelId() != this.channelOfBot) {
boolean moveBackSuccessful = bot.getApi().moveClient(idOfBot, channelOfBot);
if (!moveBackSuccessful) {
try {
bot.getApi().moveQuery(channelOfBot);
} catch (TS3CommandFailedException ex) {
logger.warn("Couldn't move bot back to his channel");
}
}
Expand Down
115 changes: 64 additions & 51 deletions src/main/java/de/halfminer/hmbot/HalfminerBot.java
Expand Up @@ -4,6 +4,7 @@
import com.github.theholywaffle.teamspeak3.TS3Config;
import com.github.theholywaffle.teamspeak3.TS3Query;
import com.github.theholywaffle.teamspeak3.TS3Query.FloodRate;
import com.github.theholywaffle.teamspeak3.api.exception.TS3CommandFailedException;
import com.github.theholywaffle.teamspeak3.api.exception.TS3ConnectionFailedException;
import com.github.theholywaffle.teamspeak3.api.reconnect.ConnectionHandler;
import com.github.theholywaffle.teamspeak3.api.reconnect.ReconnectStrategy;
Expand All @@ -25,7 +26,7 @@
public class HalfminerBot {

private final static Logger logger = LoggerFactory.getLogger(HalfminerBot.class);
private final static Object monitor = new Object();
private final static Object mainThreadLock = new Object();
private static HalfminerBot instance;
private static boolean startBot = true;

Expand All @@ -51,9 +52,9 @@ public static void main(String[] args) {
while (startBot) {
startBot = false;
new Thread(() -> new HalfminerBot(config), "bot-launch").start();
synchronized (monitor) {
synchronized (mainThreadLock) {
try {
monitor.wait();
mainThreadLock.wait();
Thread.sleep(2000L);
} catch (InterruptedException ignored) {}
}
Expand Down Expand Up @@ -131,65 +132,77 @@ public void onDisconnect(TS3Query ts3Query) {
private void startBot() {
this.api = query.getApi();

// login to server
if (api.login(config.getString("credentials.username"), config.getPassword())) {
try {
api.login(config.getString("credentials.username"), config.getPassword());
} catch (TS3CommandFailedException e) {
stop("The provided password is not valid, quitting...", false);
return;
}

if (!api.selectVirtualServerByPort(config.getInt("ports.serverPort"))) {
stop("The provided server port is not valid, quitting...", false);
return;
}
try {
api.selectVirtualServerByPort(config.getInt("ports.serverPort"));
} catch (TS3CommandFailedException e) {
stop("The provided server port is not valid, quitting...", false);
return;
}

String nickName = config.getString("botName");
if (!api.setNickname(nickName)) {
boolean nicknameWasSet = false;
for (int i = 1; i < 10; i++) {
if (api.setNickname(nickName + i)) {
nickName = nickName + i;
logger.warn("The provided botname is already in use or invalid, using {} as nickname", nickName);
nicknameWasSet = true;
break;
}
String nickName = config.getString("botName");
if (!setNickname(nickName)) {
boolean nicknameWasSet = false;
for (int i = 1; i < 10; i++) {
if (setNickname(nickName + i)) {
nickName = nickName + i;
logger.warn("The provided botname is already in use or invalid, using {} as nickname", nickName);
nicknameWasSet = true;
break;
}
}

if (!nicknameWasSet) {
stop("The provided botname is already in use or invalid, quitting...", false);
return;
}
if (!nicknameWasSet) {
stop("The provided botname is invalid or already in use, quitting...", false);
return;
}
}

// move bot into channel
// move bot into channel
try {
List<Channel> channels = api.getChannelsByName(config.getString("botChannelName"));
if (channels == null
|| channels.isEmpty()
|| !api.moveClient(api.whoAmI().getId(), channels.get(0).getId())) {
logger.warn("The provided channelname does not exist or can't be accessed, staying in default channel");
}
api.moveQuery(channels.get(0));
} catch (TS3CommandFailedException e) {
logger.warn("The provided channelname does not exist or can't be accessed, staying in default channel");
}

if (scheduler == null) {
scheduler = new Scheduler();
} else {
scheduler.createNewThreadPool();
}
if (scheduler == null) {
scheduler = new Scheduler();
} else {
scheduler.createNewThreadPool();
}

if (storage == null) {
this.storage = new Storage();
} else {
storage.doFullReload();
}
if (storage == null) {
this.storage = new Storage();
} else {
storage.doFullReload();
}

if (listeners != null) {
api.removeTS3Listeners(listeners);
}
if (listeners != null) {
api.removeTS3Listeners(listeners);
}

listeners = new BotListeners();
api.addTS3Listeners(listeners);
api.registerAllEvents();
listeners = new BotListeners();
api.addTS3Listeners(listeners);
api.registerAllEvents();

scheduler.registerAllTasks();
scheduler.registerAllTasks();

logger.info("HalfminerBot connected successfully and ready as {}", nickName);
} else {
stop("The provided password is not valid, quitting...", false);
logger.info("HalfminerBot connected successfully and ready as {}", nickName);
}

private boolean setNickname(String nickName) {
try {
api.setNickname(nickName);
return true;
} catch (TS3CommandFailedException e) {
return false;
}
}

Expand All @@ -216,9 +229,9 @@ public void stop(String message, boolean restart) {
query.exit();
}

synchronized (monitor) {
synchronized (mainThreadLock) {
startBot = restart;
monitor.notify();
mainThreadLock.notify();
}
}

Expand Down
31 changes: 18 additions & 13 deletions src/main/java/de/halfminer/hmbot/cmd/CmdAdmin.java
@@ -1,5 +1,6 @@
package de.halfminer.hmbot.cmd;

import com.github.theholywaffle.teamspeak3.api.exception.TS3CommandFailedException;
import com.github.theholywaffle.teamspeak3.api.wrapper.Client;
import com.github.theholywaffle.teamspeak3.api.wrapper.ClientInfo;
import com.github.theholywaffle.teamspeak3.api.wrapper.DatabaseClientInfo;
Expand Down Expand Up @@ -64,16 +65,20 @@ void run() throws InvalidCommandException {
int id = command.getArgumentInt(1);
if (id > Integer.MIN_VALUE) {
// lookup by id
toLookup = api.getClientInfo(id);
try {
toLookup = api.getClientInfo(id);
} catch (TS3CommandFailedException ignored) {}
}

if (toLookup == null) {

if (isUniqueID()) {
toLookup = api.getClientByUId(lookupArg);
try {
toLookup = api.getClientByUId(lookupArg);
} catch (TS3CommandFailedException ignored) {}
} else {
List<Client> clients = api.getClientsByName(lookupArg);
if (clients != null) {
try {
List<Client> clients = api.getClientsByName(lookupArg);
if (clients.size() == 1) {
toLookup = api.getClientInfo(clients.get(0).getId());
} else {
Expand All @@ -89,10 +94,11 @@ void run() throws InvalidCommandException {
sendMessage("cmdAdminLookupList", "LIST", send.toString());
return;
}
}
} catch (TS3CommandFailedException ignored) {}
}
}

// if online client lookup was not successful add online data to header, else do offline lookup
if (toLookup != null) {
mapToSend = toLookup.getMap();
nickName = toLookup.getNickname()
Expand All @@ -105,16 +111,15 @@ void run() throws InvalidCommandException {

// no online user was found, check database
DatabaseClientInfo toLookupOffline;
if (isUniqueID()) {
toLookupOffline = api.getDatabaseClientByUId(lookupArg);
} else {
toLookupOffline = api.getDatabaseClientInfo(command.getArgumentInt(1));
}

if (toLookupOffline != null) {
try {
if (isUniqueID()) {
toLookupOffline = api.getDatabaseClientByUId(lookupArg);
} else {
toLookupOffline = api.getDatabaseClientInfo(command.getArgumentInt(1));
}
mapToSend = toLookupOffline.getMap();
nickName = toLookupOffline.getNickname() + " (Offline)";
} else {
} catch (TS3CommandFailedException e) {
sendMessage("cmdAdminLookupNotFound");
return;
}
Expand Down
11 changes: 5 additions & 6 deletions src/main/java/de/halfminer/hmbot/cmd/CmdChannel.java
@@ -1,6 +1,7 @@
package de.halfminer.hmbot.cmd;

import com.github.theholywaffle.teamspeak3.api.ChannelProperty;
import com.github.theholywaffle.teamspeak3.api.exception.TS3CommandFailedException;
import com.github.theholywaffle.teamspeak3.api.wrapper.Channel;
import com.github.theholywaffle.teamspeak3.api.wrapper.ChannelInfo;
import com.github.theholywaffle.teamspeak3.api.wrapper.Client;
Expand Down Expand Up @@ -91,10 +92,8 @@ private void createChannel() {

channelCreateProperty.put(ChannelProperty.CHANNEL_TOPIC, channelTopic);

int channelCreateID = api.createChannel(channelCreateName, channelCreateProperty);

if (channelCreateID > 0) {

try {
int channelCreateID = api.createChannel(channelCreateName, channelCreateProperty);
client.setChannelId(channelCreateID);
api.moveClient(clientInfo.getId(), channelCreateID);
api.setClientChannelGroup(channelGroupAdminId, channelCreateID, clientInfo.getDatabaseId());
Expand All @@ -109,7 +108,7 @@ private void createChannel() {

sendMessage("cmdChannelCreateSuccess", "PASSWORD", password);
logger.info("Channel created: {}", channelCreateName);
} else {
} catch (TS3CommandFailedException e) {
sendMessage("cmdChannelCreateError");
}
}
Expand Down Expand Up @@ -139,7 +138,7 @@ private void updateChannel() {
}

sendMessage("cmdChannelUpdateSuccess", "PASSWORD", password);
client.addCooldown(getClass(), 300);
addCooldown(300);
}

private String getPassword() {
Expand Down
21 changes: 11 additions & 10 deletions src/main/java/de/halfminer/hmbot/cmd/CmdRank.java
@@ -1,5 +1,6 @@
package de.halfminer.hmbot.cmd;

import com.github.theholywaffle.teamspeak3.api.exception.TS3CommandFailedException;
import com.github.theholywaffle.teamspeak3.api.wrapper.ClientInfo;
import com.github.theholywaffle.teamspeak3.api.wrapper.DatabaseClientInfo;
import com.github.theholywaffle.teamspeak3.api.wrapper.ServerGroup;
Expand Down Expand Up @@ -57,7 +58,7 @@ void run() throws InvalidCommandException {
.build();

response = httpClient.newCall(request).execute();
client.addCooldown(getClass(), 10);
addCooldown(10);
if (response.isSuccessful()) {

Gson gson = new Gson();
Expand Down Expand Up @@ -96,34 +97,34 @@ void run() throws InvalidCommandException {

if (rank.equals(oldGroupName) && oldIdentity.equals(clientInfo.getUniqueIdentifier())) {
MessageBuilder.create("cmdRankAlreadyGiven").sendMessage(clientInfo);
client.addCooldown(getClass(), 300);
addCooldown(300);
return;
}

ServerGroup oldGroup = getMatchingGroup(groupList, oldGroupName);
if (oldGroup != null) {
DatabaseClientInfo oldClient = api.getDatabaseClientByUId(oldIdentity);
boolean removed = api.removeClientFromServerGroup(oldGroup.getId(), oldClient.getDatabaseId());
if (removed) {
try {
api.removeClientFromServerGroup(oldGroup.getId(), oldClient.getDatabaseId());
logger.info("Removed client {} (dbid: {}) from group '{}'",
oldClient.getNickname(), oldClient.getDatabaseId(), oldGroup.getName());
}
} catch (TS3CommandFailedException ignored) {}

} else {
logger.warn("Couldn't remove client from old group {}, as it couldn't be found", oldGroupName);
}
}

ServerGroup newGroup = getMatchingGroup(groupList, rank);
if (newGroup != null) {
client.addCooldown(getClass(), 900);
boolean added = api.addClientToServerGroup(newGroup.getId(), clientInfo.getDatabaseId());

if (added) {
addCooldown(900);
try {
api.addClientToServerGroup(newGroup.getId(), clientInfo.getDatabaseId());
MessageBuilder.create("cmdRankSet")
.addPlaceholderReplace("GROUPNAME", newGroup.getName())
.sendMessage(clientInfo);
logger.info("Set group for client {} to '{}'", clientInfo.getNickname(), newGroup.getName());
} else {
} catch (TS3CommandFailedException e) {
logger.error("Couldn't add client {} to group '{}'", clientInfo.getNickname(), newGroup.getName());
MessageBuilder.create("cmdDispatcherUnknownError").sendMessage(clientInfo);
}
Expand Down
4 changes: 4 additions & 0 deletions src/main/java/de/halfminer/hmbot/cmd/Command.java
Expand Up @@ -42,4 +42,8 @@ void sendMessage(String messageKey, String... placeholders) {
}
builder.sendMessage(clientId);
}

void addCooldown(int cooldownSeconds) {
client.addCooldown(getClass(), cooldownSeconds);
}
}
2 changes: 1 addition & 1 deletion src/main/java/de/halfminer/hmbot/storage/ClientMap.java
Expand Up @@ -115,7 +115,7 @@ Map<Client, HalfClient> getOnlineClients(List<Client> clientList) {
if (toPut != null) {
toReturn.put(client, toPut);
} else {
logger.warn("Client {} (ID: {}) was not found in storage",
logger.info("Online client {} (ID: {}) was not found in storage, just logged in or out?",
client.getNickname(), client.getDatabaseId());
}
}
Expand Down
3 changes: 3 additions & 0 deletions src/main/java/de/halfminer/hmbot/storage/HalfClient.java
Expand Up @@ -16,6 +16,9 @@ public class HalfClient extends BotClass {
private final int databaseId;
private HalfGroup group;

/**
* Counts how many clients with this clients database/unique ID are online, as there can be multiple connections.
*/
private int onlineCount = 0;
private final Map<Class, Long> commandCooldown = new ConcurrentHashMap<>();

Expand Down

0 comments on commit 9dee697

Please sign in to comment.