Skip to content

Commit b62292a

Browse files
Fix Attachments Not Including Colors
* Fixed Database on reload timing out the server * Added an error for the db manager * Fixed an issue where the LostConnectionListener was not being compiled * Made attachments use a prepend color instead of the provided color to fix formatting * Updated FirePlugin to finalize onEnable and onDisable * Updated FirePlugin to make every variable protected * Added FirePlugin#onShutdown * Added FirePlugin#saveTranslations * Temporarily added TrueDiscordlink#migrateConfigurations * Added the property messages.to_mc_attachment_color to en.yml
1 parent fa2602c commit b62292a

6 files changed

Lines changed: 96 additions & 26 deletions

File tree

src/main/java/com/firecontroller1847/truediscordlink/DatabaseManager.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,11 +58,14 @@ public void connect() {
5858
} catch (Exception e) {
5959
e.printStackTrace();
6060
connected.set(false);
61+
this.discordlink.getLogger().info("There was an error attempting to log in to the database. Reload to try again.");
62+
return;
6163
}
6264

6365
// Initialize
6466
this.initialize();
6567

68+
// Log
6669
this.discordlink.getLogger().info("Logged in to Database!");
6770
}
6871

src/main/java/com/firecontroller1847/truediscordlink/DiscordManager.java

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@
2424
import org.javacord.api.entity.message.Message;
2525
import org.javacord.api.entity.server.Server;
2626
import org.javacord.api.entity.user.User;
27+
import org.javacord.api.event.connection.LostConnectionEvent;
28+
import org.javacord.api.listener.connection.LostConnectionListener;
2729
import org.javacord.api.util.logging.ExceptionLogger;
2830

2931
import javax.net.ssl.HttpsURLConnection;
@@ -131,7 +133,13 @@ public void shutdown() {
131133

132134
// See issue https://github.com/Javacord/Javacord/issues/598 for why we wait
133135
CountDownLatch shutdownWaiter = new CountDownLatch(1);
134-
api.addLostConnectionListener(event -> shutdownWaiter.countDown());
136+
// WARNING: Do not use LAMBDA! Otherwise compiler won't include the class for some reason...
137+
api.addLostConnectionListener(new LostConnectionListener() {
138+
@Override
139+
public void onLostConnection(LostConnectionEvent event) {
140+
shutdownWaiter.countDown();
141+
}
142+
});
135143
api.disconnect();
136144
try {
137145
shutdownWaiter.await(2, TimeUnit.MINUTES);
@@ -199,6 +207,7 @@ public void sendMinecraftMessage(Message message, boolean edit) {
199207
}
200208
}
201209

210+
// Handle message attachments
202211
if (message.getAttachments().size() > 0) {
203212
TextComponent text = buildAttachmentTextComponent(message, content);
204213
discordlink.getServer().spigot().broadcast(text);
@@ -210,7 +219,10 @@ public void sendMinecraftMessage(Message message, boolean edit) {
210219
new String[] { "%discriminator%", message.getAuthor().getDiscriminator().toString() },
211220
new String[] { "%id%", message.getAuthor().getIdAsString() }
212221
);
213-
text = text.replace("%message%", content); // Replace content after translation to prevent parsing color codes
222+
223+
// Replace content after translation to prevent parsing color codes
224+
// They are parsed earlier if the configuration option is enabled
225+
text = text.replace("%message%", content);
214226
discordlink.getServer().broadcastMessage(text);
215227
}
216228
}
@@ -236,6 +248,9 @@ public TextComponent buildAttachmentTextComponent(Message message, String conten
236248
content = discordlink.getTranslation("messages.to_mc_attachment_placeholder", true);
237249
}
238250

251+
// Prepend color
252+
content = discordlink.getTranslation("messages.to_mc_attachment_color", true) + content;
253+
239254
// Make sure only the %message% is clickable by splitting the message into three parts: pre-message, message, post-message
240255
int messageIndex = attachmentFormat.indexOf("%message%");
241256
String preMessage = attachmentFormat.substring(0, messageIndex);
@@ -276,6 +291,8 @@ public ArrayList<String[]> sendDiscordMessage(String content, boolean blocking,
276291
// Run Modifications
277292
this.modifyAddCheckMentions(atomicContent, atomicModifications, player);
278293

294+
// TODO: Add support for custom emoji parsing
295+
279296
// Send Messages
280297
this.sendDiscordBotMessage(atomicContent.get(), blocking, player);
281298
this.sendDiscordWebhookMessage(atomicContent.get(), player); // Webhooks are always blocking because of HTTP requests... Is this able to be changed?

src/main/java/com/firecontroller1847/truediscordlink/FirePlugin.java

Lines changed: 36 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -41,30 +41,30 @@
4141
* </p>
4242
*
4343
* @author FireController#1847
44-
* @version 1
44+
* @version 2
4545
*/
4646
// TODO: Add support for multiple configurations
4747
public abstract class FirePlugin extends JavaPlugin {
4848

4949
// The instance of this plugin for singleton usage.
50-
private static FirePlugin instance;
50+
protected static FirePlugin instance;
5151

5252
// Variables
53-
private FileConfiguration translations; // The translations file configuration
53+
private Path translationsFile; // The file for the translations file
54+
// TODO: Remove protected when we handle configuration migrations
55+
protected FileConfiguration translations; // The translations file configuration
5456
private LinkedHashMap<String, Thread> loops = new LinkedHashMap<>(); // Utility to allow for looping methods
5557

5658
/**
5759
* <p>
5860
* Sets up the configuration and translations and logs enablement.
5961
* <br><br>
60-
* If you choose to override this method, ensure you call the super,
61-
* otherwise you will get no benefits from extending this class. It
62-
* is recommended to instead override {@link FirePlugin#onAfterConfiguration()}.
62+
* Cannot be overridden. For similar execution, override {@link FirePlugin#onAfterConfiguration()}.
6363
* </p>
6464
* @see FirePlugin#onAfterConfiguration()
6565
*/
6666
@Override
67-
public void onEnable() {
67+
public final void onEnable() {
6868
instance = this;
6969

7070
// Called before configuring
@@ -107,11 +107,9 @@ public boolean onBeforeConfiguration() {
107107

108108
/**
109109
* <p>
110-
* This is the primary method you should use when setting up anything in your plugin.
110+
* This is the primary method you should override when setting up anything in your plugin.
111111
* <br><br>
112-
* Called after the configuration has been loaded. This method is
113-
* provided because it is called before the final logging message
114-
* has been sent.
112+
* Called after the configuration has been loaded.
115113
* <br><br>
116114
* If you return false, it will automatically disable the plugin.
117115
* Please note that it will not send an error message.
@@ -136,11 +134,23 @@ public boolean onConfigReload() {
136134
return true; // This method does nothing, it's here in case the user wants to override it.
137135
}
138136

137+
/**
138+
* This is the primary method you should override when cleaning up anything in your plugin.
139+
* <br><br>
140+
* Called before all threads have been shut down.
141+
*/
142+
public void onShutdown() {
143+
// This method does nothing, it's here in case the user wants to override it.
144+
}
145+
139146
/**
140147
* Shuts down all loops and logs disablement
141148
*/
142149
@Override
143-
public void onDisable() {
150+
public final void onDisable() {
151+
// Called before thread shutdown
152+
this.onShutdown();
153+
144154
// Shutdown Loops
145155
for (Thread thread : loops.values()) {
146156
thread.interrupt();
@@ -201,7 +211,8 @@ public Plugin loadPlugin(String plugin) {
201211
*/
202212
protected void loadTranslations() {
203213
// Destroy it if it exists
204-
if (translations != null) {
214+
if (translationsFile != null || translations != null) {
215+
translationsFile = null;
205216
translations = null;
206217
}
207218

@@ -211,31 +222,38 @@ protected void loadTranslations() {
211222
if (code == null) {
212223
code = "en";
213224
}
214-
Path filePath = Paths.get(this.getDataFolder() + "/lang/" + code + ".yml");
225+
translationsFile = Paths.get(this.getDataFolder() + "/lang/" + code + ".yml");
215226

216227
// Ensure Directories Exist
217-
Files.createDirectories(filePath.getParent());
228+
Files.createDirectories(translationsFile.getParent());
218229

219230
// Ensure File Exists
220-
if (!Files.exists(filePath)) {
231+
if (!Files.exists(translationsFile)) {
221232
try {
222233
this.saveResource("lang/" + code + ".yml", false);
223234
} catch (IllegalArgumentException e) {
224235
(new InvalidConfigurationException("Invalid language file! Using default en.yml")).printStackTrace();
225-
filePath = Paths.get(this.getDataFolder() + "/lang/en.yml");
236+
translationsFile = Paths.get(this.getDataFolder() + "/lang/en.yml");
226237
this.saveResource("lang/en.yml", false);
227238
}
228239
}
229240

230241
// Load Configuration
231242
translations = new YamlConfiguration();
232-
translations.load(filePath.toFile());
243+
translations.load(translationsFile.toFile());
233244
} catch (IOException | InvalidConfigurationException e) {
234245
e.printStackTrace();
235246
this.disable();
236247
}
237248
}
238249

250+
/**
251+
* Saves the translations configuration file.
252+
*/
253+
protected void saveTranslations() throws IOException {
254+
translations.save(translationsFile.toFile());
255+
}
256+
239257
/**
240258
* <p>
241259
* Fetches a translation from the translations configuration.

src/main/java/com/firecontroller1847/truediscordlink/TrueDiscordLink.java

Lines changed: 34 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import org.bukkit.command.PluginCommand;
99
import org.bukkit.plugin.PluginManager;
1010

11+
import java.io.IOException;
1112
import java.util.Objects;
1213

1314
public class TrueDiscordLink extends FirePlugin {
@@ -34,6 +35,15 @@ public boolean onAfterConfiguration() {
3435
return false;
3536
}
3637

38+
// Migrate configurations
39+
try {
40+
this.migrateConfigurations();
41+
} catch (Exception e) {
42+
e.printStackTrace();
43+
this.getLogger().severe("There was an error attempting to migrate the old configurations to the new ones. Please contact the developer(s), " + this.getDescription().getAuthors().get(0) + ".");
44+
return false;
45+
}
46+
3747
// Initialize Managers
3848
versionHelper = new VersionHelper(this);
3949
discordManager = new DiscordManager(this);
@@ -42,6 +52,7 @@ public boolean onAfterConfiguration() {
4252
// Register Commands
4353
PluginCommand cmdtdl = Objects.requireNonNull(this.getCommand("truediscordlink"));
4454
cmdtdl.setExecutor(new CommandTrueDiscordLink());
55+
4556
cmdtdl.setTabCompleter(new TabCompleterTrueDiscordLink());
4657

4758
// Register Events
@@ -57,9 +68,7 @@ public boolean onAfterConfiguration() {
5768
}
5869

5970
@Override
60-
public void onDisable() {
61-
super.onDisable();
62-
71+
public void onShutdown() {
6372
if (this.getConfig().getBoolean("configured")) {
6473
// Disable Discord Manager
6574
discordManager.shutdown();
@@ -69,6 +78,28 @@ public void onDisable() {
6978
}
7079
}
7180

81+
// TODO: FirePlugin should handle this stuff!
82+
private void migrateConfigurations() throws IOException {
83+
this.getLogger().info("Checking for version migrations...");
84+
boolean migrated = false;
85+
86+
// v1.0.3 -> v1.0.4
87+
if (!translations.contains("messages.to_mc_attachment_color")) {
88+
translations.set("messages.to_mc_attachment_color", "§9§n");
89+
this.getLogger().info("[en.yml] Added messages.to_mc_attachment_color");
90+
migrated = true;
91+
}
92+
93+
// Save
94+
if (migrated) {
95+
this.saveConfig();
96+
this.saveTranslations();
97+
this.getLogger().info("Migrations saved!");
98+
} else {
99+
this.getLogger().info("No migrations found!");
100+
}
101+
}
102+
72103
// Escapes formatting for Discord messages
73104
public String escapeDiscordFormatting(String content) {
74105
return content.replace("*", "\\*").replace("_", "\\_").replace("~", "\\~");

src/main/java/com/firecontroller1847/truediscordlink/commands/CommandReload.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ public boolean onCommand(CommandSender sender, Command command, String label, St
2020

2121
// Reconnect database
2222
discordlink.getDatabaseManager().disconnect();
23-
discordlink.getDatabaseManager().connect();
23+
new Thread(discordlink.getDatabaseManager()::connect).start();
2424

2525
// Send notification message
2626
sender.sendMessage(discordlink.getTranslation("config.reloaded"));

src/main/resources/lang/en.yml

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,9 @@ config:
2424
reloaded: "%prefix% Configuration reloaded!"
2525
messages:
2626
to_mc_format: "%prefix% <%nickname%> %message%"
27-
to_mc_attachment_format: "%prefix% <%nickname%> §9§n%message%"
28-
to_mc_attachment_placeholder: "§9§nOpen Attachment"
27+
to_mc_attachment_format: "%prefix% <%nickname%> %message%"
28+
to_mc_attachment_placeholder: "Open Attachment"
29+
to_mc_attachment_color: "§9§n"
2930
from_mc_webhook_format: "%message%"
3031
from_mc_bot_format: "**%name%** >> %message%"
3132
tagging:

0 commit comments

Comments
 (0)