Skip to content

Commit

Permalink
Move core to Gson
Browse files Browse the repository at this point in the history
  • Loading branch information
rtm516 committed Jun 19, 2024
1 parent 22af2a3 commit a830e1a
Show file tree
Hide file tree
Showing 11 changed files with 85 additions and 92 deletions.
2 changes: 1 addition & 1 deletion bootstrap/geyser/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ relocate("com.fasterxml.jackson")

dependencies {
api(project(":core"))
api(libs.bundles.jackson.yaml)
api(libs.bundles.jackson)
compileOnly(libs.bundles.geyser)
}

Expand Down
2 changes: 1 addition & 1 deletion bootstrap/standalone/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ plugins {

dependencies {
api(project(":core"))
api(libs.bundles.jackson.yaml)
api(libs.bundles.jackson)
api(libs.bedrock.common)

api(libs.terminalconsoleappender) {
Expand Down
3 changes: 2 additions & 1 deletion core/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ plugins {
}

dependencies {
api(libs.bundles.jackson.databind)
api(libs.gson)
api(libs.bundles.jackson)
api(libs.nimbus.jose.jwt)
api(libs.java.websocket)
api(libs.methanol)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,17 +1,13 @@
package com.rtm516.mcxboxbroadcast.core;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.net.URI;
import java.time.Instant;

public class Constants {
public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.setSerializationInclusion(JsonInclude.Include.NON_NULL)
.registerModule(new JavaTimeModule());
public static final Gson GSON = new GsonBuilder().registerTypeAdapter(Instant.class, new InstantConverter()).create();

public static final String AUTH_TITLE = "0000000048183522"; // 00000000441cc96b Nintendo Switch, 0000000048183522 Android
public static final String SCOPE = "service::user.auth.xboxlive.com::MBI_SSL";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ public List<FollowerResponse.Person> get(boolean includeFollowing, boolean inclu

// We sometimes get an empty response so don't try and parse it
if (!lastResponse.isEmpty()) {
FollowerResponse xboxFollowerResponse = Constants.OBJECT_MAPPER.readValue(lastResponse, FollowerResponse.class);
FollowerResponse xboxFollowerResponse = Constants.GSON.fromJson(lastResponse, FollowerResponse.class);

// Parse through the returned list to make sure we are friends and
// add them to the list to return
Expand Down Expand Up @@ -97,7 +97,7 @@ public List<FollowerResponse.Person> get(boolean includeFollowing, boolean inclu

// We sometimes get an empty response so don't try and parse it
if (!lastResponse.isEmpty()) {
FollowerResponse xboxSocialResponse = Constants.OBJECT_MAPPER.readValue(lastResponse, FollowerResponse.class);
FollowerResponse xboxSocialResponse = Constants.GSON.fromJson(lastResponse, FollowerResponse.class);

// Parse through the returned list to make sure we are following them and
// add them to the list to return
Expand Down Expand Up @@ -163,7 +163,7 @@ public boolean addIfRequired(String xuid, String gamertag) {

try {
HttpResponse<String> response = httpClient.send(xboxFriendStatus, HttpResponse.BodyHandlers.ofString());
FriendStatusResponse modifyResponse = Constants.OBJECT_MAPPER.readValue(response.body(), FriendStatusResponse.class);
FriendStatusResponse modifyResponse = Constants.GSON.fromJson(response.body(), FriendStatusResponse.class);

if (modifyResponse.isFollowingCaller() && modifyResponse.isFollowedByCaller()) {
return false;
Expand Down Expand Up @@ -293,33 +293,29 @@ private void internalProcess() {
// Break out of the loop, so we don't try to add more friends
break;
} else if (response.statusCode() == 400) {
FriendModifyResponse modifyResponse = Constants.OBJECT_MAPPER.readValue(response.body(), FriendModifyResponse.class);
FriendModifyResponse modifyResponse = Constants.GSON.fromJson(response.body(), FriendModifyResponse.class);
if (modifyResponse.code() == 1028) {
logger.error("Friend list full, unable to add " + entry.getValue() + " (" + entry.getKey() + ") as a friend");
break;
}

logger.warn("Failed to add " + entry.getValue() + " (" + entry.getKey() + ") as a friend: (" + response.statusCode() + ") " + response.body());
} else {
try {
FriendModifyResponse modifyResponse = Constants.OBJECT_MAPPER.readValue(response.body(), FriendModifyResponse.class);

// 1011 - The requested friend operation was forbidden.
// 1015 - An invalid request was attempted.
// 1028 - The attempted People request was rejected because it would exceed the People list limit.
// 1039 - Request could not be completed due to another request taking precedence.

if (modifyResponse.code() == 1028) {
logger.error("Friend list full, unable to add " + entry.getValue() + " (" + entry.getKey() + ") as a friend");
break;
} else if (modifyResponse.code() == 1011) {
// The friend wasn't added successfully so remove them from the list
// This seems to happen in some cases, I assume from the user blocking us or having account restrictions
toAdd.remove(entry.getKey());
// TODO Remove these people from following us (block and unblock)
}
} catch (IOException e) {
// Ignore this error as it is just a fallback
FriendModifyResponse modifyResponse = Constants.GSON.fromJson(response.body(), FriendModifyResponse.class);

// 1011 - The requested friend operation was forbidden.
// 1015 - An invalid request was attempted.
// 1028 - The attempted People request was rejected because it would exceed the People list limit.
// 1039 - Request could not be completed due to another request taking precedence.

if (modifyResponse.code() == 1028) {
logger.error("Friend list full, unable to add " + entry.getValue() + " (" + entry.getKey() + ") as a friend");
break;
} else if (modifyResponse.code() == 1011) {
// The friend wasn't added successfully so remove them from the list
// This seems to happen in some cases, I assume from the user blocking us or having account restrictions
toAdd.remove(entry.getKey());
// TODO Remove these people from following us (block and unblock)
}

logger.warn("Failed to add " + entry.getValue() + " (" + entry.getKey() + ") as a friend: (" + response.statusCode() + ") " + response.body());
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.rtm516.mcxboxbroadcast.core;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

import java.lang.reflect.Type;
import java.time.Instant;

public class InstantConverter implements JsonSerializer<Instant>, JsonDeserializer<Instant> {
@Override
public Instant deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
return Instant.parse(json.getAsString());
}

@Override
public JsonElement serialize(Instant src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(src.toString());
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package com.rtm516.mcxboxbroadcast.core;

import com.fasterxml.jackson.core.JsonProcessingException;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

Expand Down Expand Up @@ -57,12 +56,9 @@ public void onOpen(ServerHandshake serverHandshake) {
@Override
public void onMessage(String message) {
if (message.contains("ConnectionId") && firstConnectionId) {
try {
Object[] parts = Constants.OBJECT_MAPPER.readValue(message, Object[].class);
connectionId = ((Map<String, String>) parts[4]).get("ConnectionId");
firstConnectionId = false;
} catch (JsonProcessingException ignored) {
}
Object[] parts = Constants.GSON.fromJson(message, Object[].class);
connectionId = ((Map<String, String>) parts[4]).get("ConnectionId");
firstConnectionId = false;
} else {
logger.debug("Websocket message: " + message);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.rtm516.mcxboxbroadcast.core;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.gson.stream.JsonReader;
import com.rtm516.mcxboxbroadcast.core.configs.FriendSyncConfig;
import com.rtm516.mcxboxbroadcast.core.exceptions.SessionCreationException;
import com.rtm516.mcxboxbroadcast.core.exceptions.SessionUpdateException;
Expand All @@ -9,6 +9,7 @@
import org.java_websocket.util.NamedThreadFactory;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URI;
Expand Down Expand Up @@ -88,7 +89,7 @@ public void init(SessionInfo sessionInfo, FriendSyncConfig friendSyncConfig) thr
// Load sub-sessions from cache
List<String> subSessions = new ArrayList<>();
try {
subSessions = Arrays.asList(Constants.OBJECT_MAPPER.readValue(Paths.get(cache, "sub_sessions.json").toFile(), String[].class));
subSessions = Arrays.asList(Constants.GSON.fromJson(new JsonReader(new FileReader(Paths.get(cache, "sub_sessions.json").toFile())), String[].class));
} catch (IOException ignored) { }

// Create the sub-sessions in a new thread so we don't block the main thread
Expand Down Expand Up @@ -132,17 +133,13 @@ protected void updateSession() throws SessionUpdateException {
checkConnection();

String responseBody = super.updateSessionInternal(Constants.CREATE_SESSION.formatted(this.sessionInfo.getSessionId()), new CreateSessionRequest(this.sessionInfo));
try {
CreateSessionResponse sessionResponse = Constants.OBJECT_MAPPER.readValue(responseBody, CreateSessionResponse.class);
CreateSessionResponse sessionResponse = Constants.GSON.fromJson(responseBody, CreateSessionResponse.class);

// Restart if we have 28/30 session members
int players = sessionResponse.members().size();
if (players >= 28) {
logger.info("Restarting session due to " + players + "/30 players");
restart();
}
} catch (JsonProcessingException e) {
throw new SessionUpdateException("Failed to parse session response: " + e.getMessage());
// Restart if we have 28/30 session members
int players = sessionResponse.members().size();
if (players >= 28) {
logger.info("Restarting session due to " + players + "/30 players");
restart();
}
}

Expand Down Expand Up @@ -219,7 +216,7 @@ public void addSubSession(String id) {

// Update the list of sub-sessions
try {
Files.write(Paths.get(cache, "sub_sessions.json"), Constants.OBJECT_MAPPER.writeValueAsBytes(subSessionManagers.keySet()));
Files.writeString(Paths.get(cache, "sub_sessions.json"), Constants.GSON.toJson(subSessionManagers.keySet()));
} catch (IOException e) {
coreLogger.error("Failed to update sub-session list", e);
}
Expand Down Expand Up @@ -252,7 +249,7 @@ public void removeSubSession(String id) {

// Update the list of sub-sessions
try {
Files.write(Paths.get(cache, "sub_sessions.json"), Constants.OBJECT_MAPPER.writeValueAsBytes(subSessionManagers.keySet()));
Files.writeString(Paths.get(cache, "sub_sessions.json"), Constants.GSON.toJson(subSessionManagers.keySet()));
} catch (IOException e) {
coreLogger.error("Failed to update sub-session list", e);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package com.rtm516.mcxboxbroadcast.core;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.github.mizosoft.methanol.Methanol;
import com.rtm516.mcxboxbroadcast.core.exceptions.SessionCreationException;
import com.rtm516.mcxboxbroadcast.core.exceptions.SessionUpdateException;
Expand Down Expand Up @@ -248,25 +247,20 @@ private void createSession() throws SessionCreationException, SessionUpdateExcep
);

// Make the request to create the session handle
HttpRequest createHandleRequest;
try {
createHandleRequest = HttpRequest.newBuilder()
.uri(Constants.CREATE_HANDLE)
.header("Content-Type", "application/json")
.header("Authorization", token)
.header("x-xbl-contract-version", "107")
.POST(HttpRequest.BodyPublishers.ofString(Constants.OBJECT_MAPPER.writeValueAsString(createHandleContent)))
.build();
} catch (JsonProcessingException e) {
throw new SessionCreationException("Unable to create session handle, error parsing json: " + e.getMessage());
}
HttpRequest createHandleRequest = HttpRequest.newBuilder()
.uri(Constants.CREATE_HANDLE)
.header("Content-Type", "application/json")
.header("Authorization", token)
.header("x-xbl-contract-version", "107")
.POST(HttpRequest.BodyPublishers.ofString(Constants.GSON.toJson(createHandleContent)))
.build();

// Read the handle response
HttpResponse<String> createHandleResponse;
try {
createHandleResponse = httpClient.send(createHandleRequest, HttpResponse.BodyHandlers.ofString());
if (this.sessionInfo != null) {
CreateHandleResponse parsedResponse = Constants.OBJECT_MAPPER.readValue(createHandleResponse.body(), CreateHandleResponse.class);
CreateHandleResponse parsedResponse = Constants.GSON.fromJson(createHandleResponse.body(), CreateHandleResponse.class);
sessionInfo.setHandleId(parsedResponse.id());
}
} catch (IOException | InterruptedException e) {
Expand Down Expand Up @@ -298,18 +292,13 @@ private void createSession() throws SessionCreationException, SessionUpdateExcep
* @throws SessionUpdateException If the update fails
*/
protected String updateSessionInternal(String url, Object data) throws SessionUpdateException {
HttpRequest createSessionRequest;
try {
createSessionRequest = HttpRequest.newBuilder()
.uri(URI.create(url))
.header("Content-Type", "application/json")
.header("Authorization", getTokenHeader())
.header("x-xbl-contract-version", "107")
.PUT(HttpRequest.BodyPublishers.ofString(Constants.OBJECT_MAPPER.writeValueAsString(data)))
.build();
} catch (JsonProcessingException e) {
throw new SessionUpdateException("Unable to update session information, error parsing json: " + e.getMessage());
}
HttpRequest createSessionRequest = HttpRequest.newBuilder()
.uri(URI.create(url))
.header("Content-Type", "application/json")
.header("Authorization", getTokenHeader())
.header("x-xbl-contract-version", "107")
.PUT(HttpRequest.BodyPublishers.ofString(Constants.GSON.toJson(data)))
.build();

HttpResponse<String> createSessionResponse;
try {
Expand Down Expand Up @@ -439,7 +428,7 @@ public SocialSummaryResponse socialSummary() {


try {
return Constants.OBJECT_MAPPER.readValue(httpClient.send(socialSummaryRequest, HttpResponse.BodyHandlers.ofString()).body(), SocialSummaryResponse.class);
return Constants.GSON.fromJson(httpClient.send(socialSummaryRequest, HttpResponse.BodyHandlers.ofString()).body(), SocialSummaryResponse.class);
} catch (IOException | InterruptedException e) {
logger.error("Unable to get current friend count", e);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,12 @@
package com.rtm516.mcxboxbroadcast.core.models.auth;

import com.fasterxml.jackson.annotation.JsonIgnore;

public record XboxTokenInfo(
String userXUID,
String userHash,
String gamertag,
String XSTSToken,
String expiresOn) {

@JsonIgnore
public String tokenHeader() {
return "XBL3.0 x=" + this.userHash + ";" + this.XSTSToken;
}
Expand Down
11 changes: 4 additions & 7 deletions gradle/libs.versions.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,17 @@ jline = "3.23.0"
terminalconsoleappender = "1.3.0"
methanol = "1.7.0"
minecraftauth = "4.0.3-SNAPSHOT"
gson = "2.11.0"

[libraries]
bedrock-common = { group = "com.nukkitx.protocol", name = "bedrock-common", version.ref = "bedrock-common" }
geyser-api = { group = "org.geysermc.geyser", name = "api", version.ref = "geyser" }
geyser-core = { group = "org.geysermc.geyser", name = "core", version.ref = "geyser" }

jackson-core = { group = "com.fasterxml.jackson.core", name = "jackson-core", version.ref = "jackson" }
jackson-databind = { group = "com.fasterxml.jackson.core", name = "jackson-databind", version.ref = "jackson" }
jackson-dataformat-yaml = { group = "com.fasterxml.jackson.dataformat", name = "jackson-dataformat-yaml", version.ref = "jackson" }
jackson-datatype-jsr310 = { group = "com.fasterxml.jackson.datatype", name = "jackson-datatype-jsr310", version.ref = "jackson" }

gson = { group = "com.google.code.gson", name = "gson", version.ref = "gson"}

java-websocket = { group = "org.java-websocket", name = "Java-WebSocket", version.ref = "java-websocket" }
nimbus-jose-jwt = { group = "com.nimbusds", name = "nimbus-jose-jwt", version.ref = "nimbus-jose-jwt" }
Expand All @@ -40,14 +41,10 @@ methanol = { group = "com.github.mizosoft.methanol", name = "methanol", version.
minecraftauth = { group = "net.raphimc", name = "MinecraftAuth", version.ref = "minecraftauth" }

[bundles]
jackson-yaml = [
jackson = [
"jackson-core",
"jackson-dataformat-yaml"
]
jackson-databind = [
"jackson-databind",
"jackson-datatype-jsr310"
]
geyser = [
"geyser-api",
"geyser-core"
Expand Down

0 comments on commit a830e1a

Please sign in to comment.