package com.mojang.realmsclient.client; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.mojang.logging.LogUtils; import com.mojang.realmsclient.RealmsMainScreen; import com.mojang.realmsclient.dto.BackupList; import com.mojang.realmsclient.dto.GuardedSerializer; import com.mojang.realmsclient.dto.Ops; import com.mojang.realmsclient.dto.OutboundPlayer; import com.mojang.realmsclient.dto.PendingInvite; import com.mojang.realmsclient.dto.PendingInvitesList; import com.mojang.realmsclient.dto.PingResult; import com.mojang.realmsclient.dto.PlayerInfo; import com.mojang.realmsclient.dto.PreferredRegionsDto; import com.mojang.realmsclient.dto.RealmsConfigurationDto; import com.mojang.realmsclient.dto.RealmsDescriptionDto; import com.mojang.realmsclient.dto.RealmsJoinInformation; import com.mojang.realmsclient.dto.RealmsNews; import com.mojang.realmsclient.dto.RealmsNotification; import com.mojang.realmsclient.dto.RealmsRegion; import com.mojang.realmsclient.dto.RealmsServer; import com.mojang.realmsclient.dto.RealmsServerList; import com.mojang.realmsclient.dto.RealmsServerPlayerLists; import com.mojang.realmsclient.dto.RealmsSetting; import com.mojang.realmsclient.dto.RealmsSlotUpdateDto; import com.mojang.realmsclient.dto.RealmsWorldOptions; import com.mojang.realmsclient.dto.RealmsWorldResetDto; import com.mojang.realmsclient.dto.RegionDataDto; import com.mojang.realmsclient.dto.RegionSelectionPreference; import com.mojang.realmsclient.dto.RegionSelectionPreferenceDto; import com.mojang.realmsclient.dto.Subscription; import com.mojang.realmsclient.dto.UploadInfo; import com.mojang.realmsclient.dto.WorldDownload; import com.mojang.realmsclient.dto.WorldTemplatePaginatedList; import com.mojang.realmsclient.exception.RealmsHttpException; import com.mojang.realmsclient.exception.RealmsServiceException; import com.mojang.realmsclient.exception.RetryCallException; import com.mojang.realmsclient.util.UploadTokenCache; import com.mojang.util.UndashedUuid; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import java.util.Locale; import java.util.Optional; import java.util.Set; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; import net.minecraft.SharedConstants; import net.minecraft.client.Minecraft; import net.minecraft.util.LenientJsonParser; import net.minecraft.util.Util; import org.jspecify.annotations.Nullable; import org.slf4j.Logger; public class RealmsClient { public static final RealmsClient.Environment ENVIRONMENT = Optional.ofNullable(System.getenv("realms.environment")) .or(() -> Optional.ofNullable(System.getProperty("realms.environment"))) .flatMap(RealmsClient.Environment::byName) .orElse(RealmsClient.Environment.PRODUCTION); private static final Logger LOGGER = LogUtils.getLogger(); @Nullable private static volatile RealmsClient realmsClientInstance = null; private final CompletableFuture> featureFlags; private final String sessionId; private final String username; private final Minecraft minecraft; private static final String WORLDS_RESOURCE_PATH = "worlds"; private static final String INVITES_RESOURCE_PATH = "invites"; private static final String MCO_RESOURCE_PATH = "mco"; private static final String SUBSCRIPTION_RESOURCE = "subscriptions"; private static final String ACTIVITIES_RESOURCE = "activities"; private static final String OPS_RESOURCE = "ops"; private static final String REGIONS_RESOURCE = "regions/ping/stat"; private static final String PREFERRED_REGION_RESOURCE = "regions/preferredRegions"; private static final String TRIALS_RESOURCE = "trial"; private static final String NOTIFICATIONS_RESOURCE = "notifications"; private static final String FEATURE_FLAGS_RESOURCE = "feature/v1"; private static final String PATH_LIST_ALL_REALMS = "/listUserWorldsOfType/any"; private static final String PATH_CREATE_SNAPSHOT_REALM = "/$PARENT_WORLD_ID/createPrereleaseRealm"; private static final String PATH_SNAPSHOT_ELIGIBLE_REALMS = "/listPrereleaseEligibleWorlds"; private static final String PATH_INITIALIZE = "/$WORLD_ID/initialize"; private static final String PATH_GET_LIVESTATS = "/liveplayerlist"; private static final String PATH_GET_SUBSCRIPTION = "/$WORLD_ID"; private static final String PATH_OP = "/$WORLD_ID/$PROFILE_UUID"; private static final String PATH_PUT_INTO_MINIGAMES_MODE = "/minigames/$MINIGAME_ID/$WORLD_ID"; private static final String PATH_AVAILABLE = "/available"; private static final String PATH_TEMPLATES = "/templates/$WORLD_TYPE"; private static final String PATH_WORLD_JOIN = "/v1/$ID/join/pc"; private static final String PATH_WORLD_GET = "/$ID"; private static final String PATH_WORLD_INVITES = "/$WORLD_ID"; private static final String PATH_WORLD_UNINVITE = "/$WORLD_ID/invite/$UUID"; private static final String PATH_PENDING_INVITES = "/pending"; private static final String PATH_ACCEPT_INVITE = "/accept/$INVITATION_ID"; private static final String PATH_REJECT_INVITE = "/reject/$INVITATION_ID"; private static final String PATH_UNINVITE_MYSELF = "/$WORLD_ID"; private static final String PATH_WORLD_CONFIGURE = "/$WORLD_ID/configuration"; private static final String PATH_SLOT = "/$WORLD_ID/slot/$SLOT_ID"; private static final String PATH_WORLD_OPEN = "/$WORLD_ID/open"; private static final String PATH_WORLD_CLOSE = "/$WORLD_ID/close"; private static final String PATH_WORLD_RESET = "/$WORLD_ID/reset"; private static final String PATH_DELETE_WORLD = "/$WORLD_ID"; private static final String PATH_WORLD_BACKUPS = "/$WORLD_ID/backups"; private static final String PATH_WORLD_DOWNLOAD = "/$WORLD_ID/slot/$SLOT_ID/download"; private static final String PATH_WORLD_UPLOAD = "/$WORLD_ID/backups/upload"; private static final String PATH_CLIENT_COMPATIBLE = "/client/compatible"; private static final String PATH_TOS_AGREED = "/tos/agreed"; private static final String PATH_NEWS = "/v1/news"; private static final String PATH_MARK_NOTIFICATIONS_SEEN = "/seen"; private static final String PATH_DISMISS_NOTIFICATIONS = "/dismiss"; private static final GuardedSerializer GSON = new GuardedSerializer(); public static RealmsClient getOrCreate() { Minecraft minecraftx = Minecraft.getInstance(); return getOrCreate(minecraftx); } public static RealmsClient getOrCreate(Minecraft minecraft) { String string = minecraftx.getUser().getName(); String string1 = minecraftx.getUser().getSessionId(); RealmsClient realmsClient = realmsClientInstance; if (realmsClient != null) { return realmsClient; } else { synchronized (RealmsClient.class) { RealmsClient realmsClient1 = realmsClientInstance; if (realmsClient1 != null) { return realmsClient1; } else { realmsClient1 = new RealmsClient(string1, string, minecraftx); realmsClientInstance = realmsClient1; return realmsClient1; } } } } private RealmsClient(String string, String string1, Minecraft minecraft) { this.sessionId = string; this.username = string1; this.minecraft = minecraftx; RealmsClientConfig.setProxy(minecraftx.getProxy()); this.featureFlags = CompletableFuture.supplyAsync(this::fetchFeatureFlags, Util.nonCriticalIoPool()); } public Set getFeatureFlags() { return this.featureFlags.join(); } private Set fetchFeatureFlags() { if (Minecraft.getInstance().isOfflineDeveloperMode()) { return Set.of(); } else { String string = url("feature/v1", null, false); try { String string1 = this.execute(Request.get(string, 5000, 10000)); JsonArray jsonArray = LenientJsonParser.parse(string1).getAsJsonArray(); Set set = jsonArray.asList().stream().map(JsonElement::getAsString).collect(Collectors.toSet()); LOGGER.debug("Fetched Realms feature flags: {}", set); return set; } catch (RealmsServiceException realmsServiceException) { LOGGER.error("Failed to fetch Realms feature flags", realmsServiceException); } catch (Exception exception) { LOGGER.error("Could not parse Realms feature flags", exception); } return Set.of(); } } public RealmsServerList listRealms() throws RealmsServiceException { String string = this.url("worlds"); if (RealmsMainScreen.isSnapshot()) { string = string + "/listUserWorldsOfType/any"; } String string1 = this.execute(Request.get(string)); return RealmsServerList.parse(GSON, string1); } public List listSnapshotEligibleRealms() throws RealmsServiceException { String string = this.url("worlds/listPrereleaseEligibleWorlds"); String string1 = this.execute(Request.get(string)); return RealmsServerList.parse(GSON, string1).servers(); } public RealmsServer createSnapshotRealm(Long long_) throws RealmsServiceException { String string = String.valueOf(long_); String string1 = this.url("worlds" + "/$PARENT_WORLD_ID/createPrereleaseRealm".replace("$PARENT_WORLD_ID", string)); return RealmsServer.parse(GSON, this.execute(Request.post(string1, string))); } public List getNotifications() throws RealmsServiceException { String string = this.url("notifications"); String string1 = this.execute(Request.get(string)); return RealmsNotification.parseList(string1); } private static JsonArray uuidListToJsonArray(List list) { JsonArray jsonArray = new JsonArray(); for (UUID uUID : list) { if (uUID != null) { jsonArray.add(uUID.toString()); } } return jsonArray; } public void notificationsSeen(List list) throws RealmsServiceException { String string = this.url("notifications/seen"); this.execute(Request.post(string, GSON.toJson(uuidListToJsonArray(list)))); } public void notificationsDismiss(List list) throws RealmsServiceException { String string = this.url("notifications/dismiss"); this.execute(Request.post(string, GSON.toJson(uuidListToJsonArray(list)))); } public RealmsServer getOwnRealm(long l) throws RealmsServiceException { String string = this.url("worlds" + "/$ID".replace("$ID", String.valueOf(l))); String string1 = this.execute(Request.get(string)); return RealmsServer.parse(GSON, string1); } public PreferredRegionsDto getPreferredRegionSelections() throws RealmsServiceException { String string = this.url("regions/preferredRegions"); String string1 = this.execute(Request.get(string)); try { PreferredRegionsDto preferredRegionsDto = GSON.fromJson(string1, PreferredRegionsDto.class); if (preferredRegionsDto == null) { return PreferredRegionsDto.empty(); } else { Set set = preferredRegionsDto.regionData().stream().map(RegionDataDto::region).collect(Collectors.toSet()); for (RealmsRegion realmsRegion : RealmsRegion.values()) { if (realmsRegion != RealmsRegion.INVALID_REGION && !set.contains(realmsRegion)) { LOGGER.debug("No realms region matching {} in server response", realmsRegion); } } return preferredRegionsDto; } } catch (Exception exception) { LOGGER.error("Could not parse PreferredRegionSelections", exception); return PreferredRegionsDto.empty(); } } public RealmsServerPlayerLists getLiveStats() throws RealmsServiceException { String string = this.url("activities/liveplayerlist"); String string1 = this.execute(Request.get(string)); return RealmsServerPlayerLists.parse(string1); } public RealmsJoinInformation join(long l) throws RealmsServiceException { String string = this.url("worlds" + "/v1/$ID/join/pc".replace("$ID", l + "")); String string1 = this.execute(Request.get(string, 5000, 30000)); return RealmsJoinInformation.parse(GSON, string1); } public void initializeRealm(long l, String string, String string1) throws RealmsServiceException { RealmsDescriptionDto realmsDescriptionDto = new RealmsDescriptionDto(string, string1); String string2 = this.url("worlds" + "/$WORLD_ID/initialize".replace("$WORLD_ID", String.valueOf(l))); String string3 = GSON.toJson(realmsDescriptionDto); this.execute(Request.post(string2, string3, 5000, 10000)); } public boolean hasParentalConsent() throws RealmsServiceException { String string = this.url("mco/available"); String string1 = this.execute(Request.get(string)); return Boolean.parseBoolean(string1); } public RealmsClient.CompatibleVersionResponse clientCompatible() throws RealmsServiceException { String string = this.url("mco/client/compatible"); String string1 = this.execute(Request.get(string)); try { return RealmsClient.CompatibleVersionResponse.valueOf(string1); } catch (IllegalArgumentException illegalArgumentException) { throw new RealmsServiceException(RealmsError.CustomError.unknownCompatibilityResponse(string1)); } } public void uninvite(long l, UUID uUID) throws RealmsServiceException { String string = this.url("invites" + "/$WORLD_ID/invite/$UUID".replace("$WORLD_ID", String.valueOf(l)).replace("$UUID", UndashedUuid.toString(uUID))); this.execute(Request.delete(string)); } public void uninviteMyselfFrom(long l) throws RealmsServiceException { String string = this.url("invites" + "/$WORLD_ID".replace("$WORLD_ID", String.valueOf(l))); this.execute(Request.delete(string)); } public List invite(long l, String string) throws RealmsServiceException { OutboundPlayer outboundPlayer = new OutboundPlayer(); outboundPlayer.name = string; String string1 = this.url("invites" + "/$WORLD_ID".replace("$WORLD_ID", String.valueOf(l))); String string2 = this.execute(Request.post(string1, GSON.toJson(outboundPlayer))); return RealmsServer.parse(GSON, string2).players; } public BackupList backupsFor(long l) throws RealmsServiceException { String string = this.url("worlds" + "/$WORLD_ID/backups".replace("$WORLD_ID", String.valueOf(l))); String string1 = this.execute(Request.get(string)); return BackupList.parse(string1); } public void updateConfiguration( long l, String string, String string1, @Nullable RegionSelectionPreferenceDto regionSelectionPreferenceDto, int i, RealmsWorldOptions realmsWorldOptions, List list ) throws RealmsServiceException { RegionSelectionPreferenceDto regionSelectionPreferenceDto1 = regionSelectionPreferenceDto != null ? regionSelectionPreferenceDto : new RegionSelectionPreferenceDto(RegionSelectionPreference.DEFAULT_SELECTION, null); RealmsDescriptionDto realmsDescriptionDto = new RealmsDescriptionDto(string, string1); RealmsSlotUpdateDto realmsSlotUpdateDto = new RealmsSlotUpdateDto(i, realmsWorldOptions, RealmsSetting.isHardcore(list)); RealmsConfigurationDto realmsConfigurationDto = new RealmsConfigurationDto(realmsSlotUpdateDto, list, regionSelectionPreferenceDto1, realmsDescriptionDto); String string2 = this.url("worlds" + "/$WORLD_ID/configuration".replace("$WORLD_ID", String.valueOf(l))); this.execute(Request.post(string2, GSON.toJson(realmsConfigurationDto))); } public void updateSlot(long l, int i, RealmsWorldOptions realmsWorldOptions, List list) throws RealmsServiceException { String string = this.url("worlds" + "/$WORLD_ID/slot/$SLOT_ID".replace("$WORLD_ID", String.valueOf(l)).replace("$SLOT_ID", String.valueOf(i))); String string1 = GSON.toJson(new RealmsSlotUpdateDto(i, realmsWorldOptions, RealmsSetting.isHardcore(list))); this.execute(Request.post(string, string1)); } public boolean switchSlot(long l, int i) throws RealmsServiceException { String string = this.url("worlds" + "/$WORLD_ID/slot/$SLOT_ID".replace("$WORLD_ID", String.valueOf(l)).replace("$SLOT_ID", String.valueOf(i))); String string1 = this.execute(Request.put(string, "")); return Boolean.valueOf(string1); } public void restoreWorld(long l, String string) throws RealmsServiceException { String string1 = this.url("worlds" + "/$WORLD_ID/backups".replace("$WORLD_ID", String.valueOf(l)), "backupId=" + string); this.execute(Request.put(string1, "", 40000, 600000)); } public WorldTemplatePaginatedList fetchWorldTemplates(int i, int j, RealmsServer.WorldType worldType) throws RealmsServiceException { String string = this.url( "worlds" + "/templates/$WORLD_TYPE".replace("$WORLD_TYPE", worldType.toString()), String.format(Locale.ROOT, "page=%d&pageSize=%d", i, j) ); String string1 = this.execute(Request.get(string)); return WorldTemplatePaginatedList.parse(string1); } public Boolean putIntoMinigameMode(long l, String string) throws RealmsServiceException { String string1 = "/minigames/$MINIGAME_ID/$WORLD_ID".replace("$MINIGAME_ID", string).replace("$WORLD_ID", String.valueOf(l)); String string2 = this.url("worlds" + string1); return Boolean.valueOf(this.execute(Request.put(string2, ""))); } public Ops op(long l, UUID uUID) throws RealmsServiceException { String string = "/$WORLD_ID/$PROFILE_UUID".replace("$WORLD_ID", String.valueOf(l)).replace("$PROFILE_UUID", UndashedUuid.toString(uUID)); String string1 = this.url("ops" + string); return Ops.parse(this.execute(Request.post(string1, ""))); } public Ops deop(long l, UUID uUID) throws RealmsServiceException { String string = "/$WORLD_ID/$PROFILE_UUID".replace("$WORLD_ID", String.valueOf(l)).replace("$PROFILE_UUID", UndashedUuid.toString(uUID)); String string1 = this.url("ops" + string); return Ops.parse(this.execute(Request.delete(string1))); } public Boolean open(long l) throws RealmsServiceException { String string = this.url("worlds" + "/$WORLD_ID/open".replace("$WORLD_ID", String.valueOf(l))); String string1 = this.execute(Request.put(string, "")); return Boolean.valueOf(string1); } public Boolean close(long l) throws RealmsServiceException { String string = this.url("worlds" + "/$WORLD_ID/close".replace("$WORLD_ID", String.valueOf(l))); String string1 = this.execute(Request.put(string, "")); return Boolean.valueOf(string1); } public Boolean resetWorldWithTemplate(long l, String string) throws RealmsServiceException { RealmsWorldResetDto realmsWorldResetDto = new RealmsWorldResetDto(null, Long.valueOf(string), -1, false, Set.of()); String string1 = this.url("worlds" + "/$WORLD_ID/reset".replace("$WORLD_ID", String.valueOf(l))); String string2 = this.execute(Request.post(string1, GSON.toJson(realmsWorldResetDto), 30000, 80000)); return Boolean.valueOf(string2); } public Subscription subscriptionFor(long l) throws RealmsServiceException { String string = this.url("subscriptions" + "/$WORLD_ID".replace("$WORLD_ID", String.valueOf(l))); String string1 = this.execute(Request.get(string)); return Subscription.parse(string1); } public int pendingInvitesCount() throws RealmsServiceException { return this.pendingInvites().pendingInvites().size(); } public PendingInvitesList pendingInvites() throws RealmsServiceException { String string = this.url("invites/pending"); String string1 = this.execute(Request.get(string)); PendingInvitesList pendingInvitesList = PendingInvitesList.parse(string1); pendingInvitesList.pendingInvites().removeIf(this::isBlocked); return pendingInvitesList; } private boolean isBlocked(PendingInvite pendingInvite) { return this.minecraft.getPlayerSocialManager().isBlocked(pendingInvite.realmOwnerUuid()); } public void acceptInvitation(String string) throws RealmsServiceException { String string1 = this.url("invites" + "/accept/$INVITATION_ID".replace("$INVITATION_ID", string)); this.execute(Request.put(string1, "")); } public WorldDownload requestDownloadInfo(long l, int i) throws RealmsServiceException { String string = this.url("worlds" + "/$WORLD_ID/slot/$SLOT_ID/download".replace("$WORLD_ID", String.valueOf(l)).replace("$SLOT_ID", String.valueOf(i))); String string1 = this.execute(Request.get(string)); return WorldDownload.parse(string1); } @Nullable public UploadInfo requestUploadInfo(long l) throws RealmsServiceException { String string = this.url("worlds" + "/$WORLD_ID/backups/upload".replace("$WORLD_ID", String.valueOf(l))); String string1 = UploadTokenCache.get(l); UploadInfo uploadInfo = UploadInfo.parse(this.execute(Request.put(string, UploadInfo.createRequest(string1)))); if (uploadInfo != null) { UploadTokenCache.put(l, uploadInfo.token()); } return uploadInfo; } public void rejectInvitation(String string) throws RealmsServiceException { String string1 = this.url("invites" + "/reject/$INVITATION_ID".replace("$INVITATION_ID", string)); this.execute(Request.put(string1, "")); } public void agreeToTos() throws RealmsServiceException { String string = this.url("mco/tos/agreed"); this.execute(Request.post(string, "")); } public RealmsNews getNews() throws RealmsServiceException { String string = this.url("mco/v1/news"); String string1 = this.execute(Request.get(string, 5000, 10000)); return RealmsNews.parse(string1); } public void sendPingResults(PingResult pingResult) throws RealmsServiceException { String string = this.url("regions/ping/stat"); this.execute(Request.post(string, GSON.toJson(pingResult))); } public Boolean trialAvailable() throws RealmsServiceException { String string = this.url("trial"); String string1 = this.execute(Request.get(string)); return Boolean.valueOf(string1); } public void deleteRealm(long l) throws RealmsServiceException { String string = this.url("worlds" + "/$WORLD_ID".replace("$WORLD_ID", String.valueOf(l))); this.execute(Request.delete(string)); } private String url(String string) throws RealmsServiceException { return this.url(string, null); } private String url(String string, @Nullable String string1) { return url(string, string1, this.getFeatureFlags().contains("realms_in_aks")); } private static String url(String string, @Nullable String string1, boolean bl) { try { return new URI(ENVIRONMENT.protocol, bl ? ENVIRONMENT.alternativeUrl : ENVIRONMENT.baseUrl, "/" + string, string1, null).toASCIIString(); } catch (URISyntaxException uRISyntaxException) { throw new IllegalArgumentException(string, uRISyntaxException); } } private String execute(Request request) throws RealmsServiceException { request.cookie("sid", this.sessionId); request.cookie("user", this.username); request.cookie("version", SharedConstants.getCurrentVersion().name()); request.addSnapshotHeader(RealmsMainScreen.isSnapshot()); try { int i = request.responseCode(); if (i != 503 && i != 277) { String string1 = request.text(); if (i >= 200 && i < 300) { return string1; } else if (i == 401) { String string2 = request.getHeader("WWW-Authenticate"); LOGGER.info("Could not authorize you against Realms server: {}", string2); throw new RealmsServiceException(new RealmsError.AuthenticationError(string2)); } else { String string = request.connection.getContentType(); if (string != null && string.startsWith("text/html")) { throw new RealmsServiceException(RealmsError.CustomError.htmlPayload(i, string1)); } else { RealmsError realmsError = RealmsError.parse(i, string1); throw new RealmsServiceException(realmsError); } } } else { int j = request.getRetryAfterHeader(); throw new RetryCallException(j, i); } } catch (RealmsHttpException realmsHttpException) { throw new RealmsServiceException(RealmsError.CustomError.connectivityError(realmsHttpException)); } } public static enum CompatibleVersionResponse { COMPATIBLE, OUTDATED, OTHER; } public static enum Environment { PRODUCTION("pc.realms.minecraft.net", "java.frontendlegacy.realms.minecraft-services.net", "https"), STAGE("pc-stage.realms.minecraft.net", "java.frontendlegacy.stage-c2a40e62.realms.minecraft-services.net", "https"), LOCAL("localhost:8080", "localhost:8080", "http"); public final String baseUrl; public final String alternativeUrl; public final String protocol; private Environment(final String string1, final String string2, final String string3) { this.baseUrl = string1; this.alternativeUrl = string2; this.protocol = string3; } public static Optional byName(String string) { String string1 = string.toLowerCase(Locale.ROOT); return switch (string1) { case "production" -> Optional.of(PRODUCTION); case "local" -> Optional.of(LOCAL); case "stage", "staging" -> Optional.of(STAGE); default -> Optional.empty(); }; } } }