Skip to content

Commit bafba69

Browse files
committed
Clean-up code and improve status messages
1 parent e37227c commit bafba69

9 files changed

Lines changed: 347 additions & 286 deletions

File tree

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
package com.rtm516.mcxboxbroadcast.bootstrap.geyser;
2+
3+
import com.fasterxml.jackson.databind.DeserializationFeature;
4+
import com.fasterxml.jackson.databind.ObjectMapper;
5+
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
6+
import org.geysermc.geyser.api.extension.Extension;
7+
8+
import java.io.File;
9+
import java.io.FileWriter;
10+
import java.io.IOException;
11+
import java.io.InputStream;
12+
import java.net.URISyntaxException;
13+
import java.nio.file.FileSystem;
14+
import java.nio.file.FileSystems;
15+
import java.nio.file.Files;
16+
import java.util.Collections;
17+
18+
public class ConfigLoader {
19+
public static <T> T load(Extension extension, Class<?> extensionClass, Class<T> configClass) {
20+
File configFile = extension.dataFolder().resolve("config.yml").toFile();
21+
22+
// Ensure the data folder exists
23+
if (!extension.dataFolder().toFile().exists()) {
24+
if (!extension.dataFolder().toFile().mkdirs()) {
25+
extension.logger().error("Failed to create data folder");
26+
return null;
27+
}
28+
}
29+
30+
// Create the config file if it doesn't exist
31+
if (!configFile.exists()) {
32+
try (FileWriter writer = new FileWriter(configFile)) {
33+
try (FileSystem fileSystem = FileSystems.newFileSystem(new File(extensionClass.getProtectionDomain().getCodeSource().getLocation().toURI()).toPath(), Collections.emptyMap())) {
34+
try (InputStream input = Files.newInputStream(fileSystem.getPath("config.yml"))) {
35+
byte[] bytes = new byte[input.available()];
36+
37+
input.read(bytes);
38+
39+
writer.write(new String(bytes).toCharArray());
40+
41+
writer.flush();
42+
}
43+
}
44+
} catch (IOException | URISyntaxException e) {
45+
extension.logger().error("Failed to create config", e);
46+
return null;
47+
}
48+
}
49+
50+
// Load the config file
51+
try {
52+
return new ObjectMapper(new YAMLFactory())
53+
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
54+
.readValue(configFile, configClass);
55+
} catch (IOException e) {
56+
extension.logger().error("Failed to load config", e);
57+
return null;
58+
}
59+
}
60+
}

bootstrap/geyser/src/main/java/com/rtm516/mcxboxbroadcast/bootstrap/geyser/MCXboxBroadcastExtension.java

Lines changed: 9 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22

33
import com.fasterxml.jackson.databind.ObjectMapper;
44
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
5-
import com.rtm516.mcxboxbroadcast.core.FriendUtils;
65
import com.rtm516.mcxboxbroadcast.core.Logger;
76
import com.rtm516.mcxboxbroadcast.core.SessionInfo;
87
import com.rtm516.mcxboxbroadcast.core.SessionManager;
@@ -17,7 +16,6 @@
1716
import org.geysermc.geyser.GeyserImpl;
1817
import org.geysermc.geyser.api.command.Command;
1918
import org.geysermc.geyser.api.command.CommandSource;
20-
import org.geysermc.geyser.api.connection.GeyserConnection;
2119
import org.geysermc.geyser.api.event.lifecycle.GeyserDefineCommandsEvent;
2220
import org.geysermc.geyser.api.event.lifecycle.GeyserPostInitializeEvent;
2321
import org.geysermc.geyser.api.extension.Extension;
@@ -45,8 +43,6 @@ public class MCXboxBroadcastExtension implements Extension {
4543
SessionManager sessionManager;
4644
SessionInfo sessionInfo;
4745
ExtensionConfig config;
48-
private ScheduledFuture<?> updateTimerScheduledFuture;
49-
private ScheduledFuture<?> friendTimerScheduledFuture;
5046

5147
@Subscribe
5248
public void onCommandDefine(GeyserDefineCommandsEvent event) {
@@ -60,14 +56,7 @@ public void onCommandDefine(GeyserDefineCommandsEvent event) {
6056
return;
6157
}
6258

63-
sessionManager.stopSession();
64-
65-
if (updateTimerScheduledFuture != null) {
66-
updateTimerScheduledFuture.cancel(true);
67-
}
68-
if (friendTimerScheduledFuture != null) {
69-
friendTimerScheduledFuture.cancel(true);
70-
}
59+
sessionManager.shutdown();
7160

7261
sessionManager = new SessionManager(this.dataFolder().toString(), logger);
7362

@@ -95,34 +84,8 @@ public void onPostInitialize(GeyserPostInitializeEvent event) {
9584
logger = new ExtensionLoggerImpl(this.logger());
9685
sessionManager = new SessionManager(this.dataFolder().toString(), logger);
9786

98-
File configFile = this.dataFolder().resolve("config.yml").toFile();
99-
100-
// Create the config file if it doesn't exist
101-
if (!configFile.exists()) {
102-
try (FileWriter writer = new FileWriter(configFile)) {
103-
try (FileSystem fileSystem = FileSystems.newFileSystem(new File(MCXboxBroadcastExtension.class.getProtectionDomain().getCodeSource().getLocation().toURI()).toPath(), Collections.emptyMap())) {
104-
try (InputStream input = Files.newInputStream(fileSystem.getPath("config.yml"))) {
105-
byte[] bytes = new byte[input.available()];
106-
107-
input.read(bytes);
108-
109-
writer.write(new String(bytes).toCharArray());
110-
111-
writer.flush();
112-
}
113-
}
114-
} catch (IOException | URISyntaxException e) {
115-
logger.error("Failed to create config", e);
116-
return;
117-
}
118-
}
119-
120-
try {
121-
config = new ObjectMapper(new YAMLFactory()).readValue(configFile, ExtensionConfig.class);
122-
} catch (IOException e) {
123-
logger.error("Failed to load config", e);
124-
return;
125-
}
87+
// Load the config file
88+
config = ConfigLoader.load(this, MCXboxBroadcastExtension.class, ExtensionConfig.class);
12689

12790
// Pull onto another thread so we don't hang the main thread
12891
new Thread(() -> {
@@ -172,33 +135,24 @@ public void onPostInitialize(GeyserPostInitializeEvent event) {
172135
private void createSession() {
173136
// Create the Xbox session
174137
try {
175-
logger.info("Setting up Xbox session...");
176-
sessionManager.createSession(sessionInfo);
177-
sessionManager.updatePresence();
178-
logger.info("Created Xbox session!");
138+
sessionManager.init(sessionInfo);
179139
} catch (SessionCreationException | SessionUpdateException e) {
180140
logger.error("Failed to create xbox session!", e);
181141
return;
182142
}
183143

184-
// Start the update timer
185-
updateTimerScheduledFuture = GeyserImpl.getInstance().getScheduledThread().scheduleWithFixedDelay(this::tick, config.updateInterval(), config.updateInterval(), TimeUnit.SECONDS); // TODO Find API equivalent
144+
// Set up the auto friend sync
145+
sessionManager.friendManager().initAutoFriend(config.friendSync());
186146

187-
// Start a timer for the friend sync if enabled
188-
if (config.friendSync().autoFollow() || config.friendSync().autoUnfollow()) {
189-
friendTimerScheduledFuture = GeyserImpl.getInstance().getScheduledThread().scheduleAtFixedRate(() -> FriendUtils.autoFriend(sessionManager, logger, config.friendSync()), config.friendSync().updateInterval(), config.friendSync().updateInterval(), TimeUnit.SECONDS);
190-
}
147+
// Start the update timer
148+
sessionManager.scheduledThread().scheduleWithFixedDelay(this::tick, config.updateInterval(), config.updateInterval(), TimeUnit.SECONDS);
191149
}
192150

193151
private void tick() {
194-
// Make sure the connection is still active
195-
sessionManager.checkConnection();
196-
197152
// Update the player count for the session
198153
try {
199154
sessionInfo.setPlayers(this.geyserApi().onlineConnections().size());
200155
sessionManager.updateSession(sessionInfo);
201-
sessionManager.updatePresence();
202156
} catch (SessionUpdateException e) {
203157
logger.error("Failed to update session information!", e);
204158
}
@@ -209,7 +163,7 @@ private void tick() {
209163
&& this.geyserApi().platformType() == PlatformType.SPIGOT // TODO Find API equivalent
210164
&& config.whitelistFriends()) {
211165
try {
212-
for (FollowerResponse.Person person : sessionManager.getXboxFriends()) {
166+
for (FollowerResponse.Person person : sessionManager.friendManager().get()) {
213167
if (WhitelistUtils.addPlayer(Utils.getJavaUuid(person.xuid), "unknown")) {
214168
logger.info("Added xbox friend " + person.displayName + " to whitelist");
215169
}

bootstrap/standalone/src/main/java/com/rtm516/mcxboxbroadcast/bootstrap/standalone/StandaloneMain.java

Lines changed: 5 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,11 @@
44
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
55
import com.nukkitx.protocol.bedrock.BedrockClient;
66
import com.nukkitx.protocol.bedrock.BedrockPong;
7-
import com.rtm516.mcxboxbroadcast.core.FriendUtils;
87
import com.rtm516.mcxboxbroadcast.core.SessionInfo;
98
import com.rtm516.mcxboxbroadcast.core.SessionManager;
109
import com.rtm516.mcxboxbroadcast.core.configs.StandaloneConfig;
1110
import com.rtm516.mcxboxbroadcast.core.exceptions.SessionCreationException;
1211
import com.rtm516.mcxboxbroadcast.core.exceptions.SessionUpdateException;
13-
import org.java_websocket.util.NamedThreadFactory;
1412
import org.slf4j.LoggerFactory;
1513

1614
import java.io.File;
@@ -19,15 +17,12 @@
1917
import java.io.InputStream;
2018
import java.net.InetSocketAddress;
2119
import java.util.concurrent.ExecutionException;
22-
import java.util.concurrent.Executors;
23-
import java.util.concurrent.ScheduledExecutorService;
2420
import java.util.concurrent.TimeUnit;
2521

2622
public class StandaloneMain {
2723
private static StandaloneConfig config;
2824
private static StandaloneLoggerImpl logger;
2925
private static SessionInfo sessionInfo;
30-
private static ScheduledExecutorService scheduledThreadPool;
3126

3227
public static SessionManager sessionManager;
3328

@@ -78,43 +73,30 @@ public static void main(String[] args) throws Exception {
7873
}
7974

8075
public static void restart() throws SessionUpdateException, SessionCreationException {
81-
sessionManager.stopSession();
82-
scheduledThreadPool.shutdown();
76+
sessionManager.shutdown();
8377

8478
sessionManager = new SessionManager("./cache", logger);
8579

8680
createSession();
8781
}
8882

8983
private static void createSession() throws SessionCreationException, SessionUpdateException {
90-
scheduledThreadPool = Executors.newScheduledThreadPool(2, new NamedThreadFactory("Scheduled Thread"));
84+
sessionManager.init(sessionInfo);
9185

92-
logger.info("Creating session...");
86+
// Set up the auto friend sync
87+
sessionManager.friendManager().initAutoFriend(config.friendSync());
9388

94-
sessionManager.createSession(sessionInfo);
95-
sessionManager.updatePresence();
96-
97-
logger.info("Created session!");
98-
99-
scheduledThreadPool.scheduleWithFixedDelay(() -> {
89+
sessionManager.scheduledThread().scheduleWithFixedDelay(() -> {
10090
updateSessionInfo(sessionInfo);
10191

10292
try {
103-
// Make sure the connection is still active
104-
sessionManager.checkConnection();
105-
10693
// Update the session
10794
sessionManager.updateSession(sessionInfo);
108-
sessionManager.updatePresence();
10995
logger.info("Updated session!");
11096
} catch (SessionUpdateException e) {
11197
logger.error("Failed to update session", e);
11298
}
11399
}, config.session().updateInterval(), config.session().updateInterval(), TimeUnit.SECONDS);
114-
115-
if (config.friendSync().autoFollow() || config.friendSync().autoUnfollow()) {
116-
scheduledThreadPool.scheduleWithFixedDelay(() -> FriendUtils.autoFriend(sessionManager, logger, config.friendSync()), config.friendSync().updateInterval(), config.friendSync().updateInterval(), TimeUnit.SECONDS);
117-
}
118100
}
119101

120102
private static void updateSessionInfo(SessionInfo sessionInfo) {

0 commit comments

Comments
 (0)