Skip to content

Commit

Permalink
apply suggested changes to settings api
Browse files Browse the repository at this point in the history
- settings and supporter only have optional return types
- rename non api methods
- remove api version as extra attribute
- rename config_values.json to default_remote_config.json
  • Loading branch information
Cheaterpaul committed Aug 1, 2023
1 parent 9192194 commit 7661995
Show file tree
Hide file tree
Showing 9 changed files with 77 additions and 74 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/update_api.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ on:
- ${{ github.event.repository.default_branch }}
paths:
- 'src/main/resources/supporters.json'
- 'src/main/resources/config_values.json'
- 'src/main/resources/default_remote_config.json'

jobs:
upload:
Expand All @@ -22,4 +22,4 @@ jobs:
uses: wei/curl@v1
with:
args: |
-X 'POST' 'https://api.vampirism.dev/api/v1/config/set' -H 'x-api-key: ${{ secrets.VAMPIRISM_API }}' -H 'Content-Type: application/json' --upload-file src/main/resources/config_values.json
-X 'POST' 'https://api.vampirism.dev/api/v1/config/set' -H 'x-api-key: ${{ secrets.VAMPIRISM_API }}' -H 'Content-Type: application/json' --upload-file src/main/resources/default_remote_config.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,26 +18,18 @@ public interface ISettingsProvider {
* @return true if the settings value exists and the value is {@code true}
*/
@Contract(pure = true)
boolean isSettingTrue(String key);
boolean isSettingTrue(@NotNull String key);

/**
* @param key settings key
* @return settings value for the given key
*/
@NotNull
@Contract(pure = true)
Optional<String> getSettingsValueOpt(String key);

/**
* @param key settings key
* @return settings value for the given key
*/
@Nullable
@Contract(pure = true)
String getSettingsValue(String key);
Optional<String> getSettingsValue(@NotNull String key);

@NotNull
CompletableFuture<Collection<Supporter>> getSupportersAsync();
CompletableFuture<Optional<Collection<Supporter>>> getSupportersAsync();

/**
* updates the cache of the settings
Expand Down
17 changes: 17 additions & 0 deletions src/api/java/de/teamlapen/vampirism/api/settings/Supporter.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,25 @@
package de.teamlapen.vampirism.api.settings;

import de.teamlapen.vampirism.api.VReference;
import net.minecraft.resources.ResourceLocation;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public record Supporter(@NotNull ResourceLocation faction, @NotNull String name, @NotNull String texture, int typeId, @Nullable String bookId) {

public record Old(@NotNull String name, String texture, int type, int status) {
public Supporter toNew(ResourceLocation faction) {
return new Supporter(faction, name, texture, type, null);
}
}
public record OldList(@NotNull String comment, @NotNull List<Old> vampires, @NotNull List<Old> hunters) {
public Collection<Supporter> toNew() {
return Stream.concat(vampires.stream().map(s -> s.toNew(VReference.VAMPIRE_FACTION.getID())), hunters.stream().map(s -> s.toNew(VReference.HUNTER_FACTION.getID()))).collect(Collectors.toList());
}
}
}
3 changes: 1 addition & 2 deletions src/main/java/de/teamlapen/vampirism/REFERENCE.java
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,7 @@ public class REFERENCE {
public static final String CURSEFORGE_LINK = "https://minecraft.curseforge.com/projects/vampirism-become-a-vampire";
public static final String GUIDEAPI_LINK = "https://www.curseforge.com/minecraft/mc-mods/guide-api-village-and-pillage";
public static final String INTEGRATIONS_LINK = "https://minecraft.curseforge.com/projects/vampirism-integrations";
public static final String SETTINGS_API = "https://api.vampirism.dev/api";
public static final String SETTINGS_API_VERSION = "v1";
public static final String SETTINGS_API = "https://api.vampirism.dev/api/v1";

// fixed values
public static final ResourceLocation FACTION_PLAYER_HANDLER_KEY = new ResourceLocation(MODID, "ifactionplayerhandler");
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/de/teamlapen/vampirism/VampirismMod.java
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ private void loadComplete(final @NotNull FMLLoadCompleteEvent event) {
*/
private void prepareAPI() {

VampirismAPI.setUpRegistries(new FactionRegistry(), new SundamageRegistry(), new VampirismEntityRegistry().setDefaultConvertingHandlerCreator(DefaultConvertingHandler::new), new ActionManager(), new SkillManager(), new VampireVisionRegistry(), new ActionManagerEntity(), new ExtendedBrewingRecipeRegistry(), new SettingsProvider(REFERENCE.SETTINGS_API, REFERENCE.SETTINGS_API_VERSION));
VampirismAPI.setUpRegistries(new FactionRegistry(), new SundamageRegistry(), new VampirismEntityRegistry().setDefaultConvertingHandlerCreator(DefaultConvertingHandler::new), new ActionManager(), new SkillManager(), new VampireVisionRegistry(), new ActionManagerEntity(), new ExtendedBrewingRecipeRegistry(), new SettingsProvider(REFERENCE.SETTINGS_API));
DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> proxy::setupAPIClient);

VReference.VAMPIRE_FACTION = VampirismAPI.factionRegistry()
Expand Down
95 changes: 44 additions & 51 deletions src/main/java/de/teamlapen/vampirism/misc/SettingsProvider.java
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
package de.teamlapen.vampirism.misc;

import com.google.common.io.ByteStreams;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import de.teamlapen.lib.lib.util.ResourceLocationTypeAdapter;
import de.teamlapen.vampirism.REFERENCE;
import de.teamlapen.vampirism.VampirismMod;
import de.teamlapen.vampirism.api.VReference;
import de.teamlapen.vampirism.api.settings.ISettingsProvider;
import de.teamlapen.vampirism.api.settings.Supporter;
import net.minecraft.resources.ResourceLocation;
Expand All @@ -14,17 +17,20 @@
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.ByteBuffer;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.Flow;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class SettingsProvider implements ISettingsProvider {

Expand All @@ -33,111 +39,98 @@ public class SettingsProvider implements ISettingsProvider {

private final HttpClient client;
private final String baseUrl;
private final String apiVersion;
private final Map<String, String> settingValues = new HashMap<>();

public SettingsProvider(String baseUrl, String apiVersion) {
public SettingsProvider(String baseUrl) {
this.baseUrl = baseUrl;
this.apiVersion = apiVersion;
this.client = HttpClient.newHttpClient();
}

@Override
public void syncSettingsCache() {
getSettingValuesAsync().handleAsync(this::checkSettings).thenAccept(x -> {
retrieveSettingValuesAsync().handleAsync(this::checkSettings).thenAccept(newValues -> {
this.settingValues.clear();
this.settingValues.putAll(x);
newValues.ifPresent(this.settingValues::putAll);
});
}

@Nullable
public String getSettingsValue(String key) {
return this.settingValues.get(key);
}

public @NotNull Optional<String> getSettingsValueOpt(String key) {
@Override
public @NotNull Optional<String> getSettingsValue(@NotNull String key) {
return Optional.ofNullable(this.settingValues.get(key));
}

public boolean isSettingTrue(String key) {
@Override
public boolean isSettingTrue(@NotNull String key) {
return "true".equals(this.settingValues.get(key));
}

@Override
public @NotNull CompletableFuture<Collection<Supporter>> getSupportersAsync() {
return GetSupportersAsync().handleAsync(this::checkSupporter);
public @NotNull CompletableFuture<Optional<Collection<Supporter>>> getSupportersAsync() {
return retrieveSupportersAsync().handleAsync(this::checkSupporter);
}

@Nullable
public CompletableFuture<String> getSettingValueAsync(String key) {
return get("config/get?configId=" + key);
}

public CompletableFuture<Map<String, String>> getSettingValuesAsync() {
public CompletableFuture<Map<String, String>> retrieveSettingValuesAsync() {
return get("config/list").thenApply(x -> GSON.fromJson(x, TypeToken.getParameterized(Map.class, String.class, String.class).getType()));
}

public CompletableFuture<Map<String, String>> getSettingValuesAsync(String modid) {
public CompletableFuture<Map<String, String>> retrieveSettingValuesAsync(String modid) {
return get("config/list?modid=" + modid).thenApply(x -> GSON.fromJson(x, TypeToken.getParameterized(Map.class, String.class, String.class).getType()));
}

public CompletableFuture<Collection<Supporter>> GetSupportersAsync() {
Type type = TypeToken.getParameterized(List.class, Supporter.class).getType();
public CompletableFuture<Collection<Supporter>> retrieveSupportersAsync() {
return get("supporter/list").thenApply(x -> GSON.fromJson(x, TypeToken.getParameterized(List.class, Supporter.class).getType()));
}

public CompletableFuture<Collection<Supporter>> GetSupportersAsync(String modid) {
return GetSupportersAsync().thenApply(x -> x.stream().filter(y -> y.faction().getNamespace().equals(modid)).collect(Collectors.toList()));
public CompletableFuture<Collection<Supporter>> retrieveSupportersAsync(String modid) {
return retrieveSupportersAsync().thenApply(x -> x.stream().filter(y -> y.faction().getNamespace().equals(modid)).collect(Collectors.toList()));
}

private CompletableFuture<String> get(String path) {
return get(this.apiVersion, path);
}

private CompletableFuture<String> get(String apiVersion, String path) {
try {
var request = HttpRequest.newBuilder(new URI(this.baseUrl + "/" + apiVersion + "/" + path)).GET().build();
var request = HttpRequest.newBuilder(new URI(this.baseUrl + "/" + path)).GET().build();
return this.client.sendAsync(request, HttpResponse.BodyHandlers.ofString()).thenApply(HttpResponse::body);
} catch (URISyntaxException e) {
return CompletableFuture.failedFuture(e);
}
}

private Map<String, String> checkSettings(Map<String, String> settings, Throwable error) {
private Optional<Map<String, String>> checkSettings(Map<String, String> settings, Throwable error) {
if (error != null) {
LOGGER.error("Failed to retrieve settings from server", error);
}
if (VampirismMod.inDev || settings == null) {
try {
InputStream inputStream = VampirismMod.class.getResourceAsStream("/config_values.json");
String data = new String(ByteStreams.toByteArray(inputStream));
inputStream.close();
return GSON.fromJson(data, TypeToken.getParameterized(Map.class, String.class, String.class).getType());
} catch (IOException e) {
LOGGER.error("Failed to retrieve supporter form resource", e);
if (settings == null) {
return Collections.emptyMap();
if (false) {
InputStream inputStream = VampirismMod.class.getResourceAsStream("/default_remote_config.json");
if (inputStream != null) {
try {
return Optional.of(GSON.fromJson(new JsonReader(new InputStreamReader(inputStream)), TypeToken.getParameterized(Map.class, String.class, String.class).getType()));
} catch (JsonSyntaxException ex) {
LOGGER.error("Failed to retrieve settings from file", ex);
}
}
}
return settings;
return Optional.ofNullable(settings);
}

private Collection<Supporter> checkSupporter(Collection<Supporter> file, Throwable error) {
private Optional<Collection<Supporter>> checkSupporter(Collection<Supporter> file, Throwable error) {
if (error != null) {
LOGGER.error("Failed to retrieve supporter from server", error);
}
if (VampirismMod.inDev || file == null) {
try {
if (false) {
InputStream inputStream = VampirismMod.class.getResourceAsStream("/supporters.json");
String data = new String(ByteStreams.toByteArray(inputStream));
inputStream.close();
return GSON.fromJson(data, TypeToken.getParameterized(List.class, Supporter.class).getType());
} catch (IOException e) {
LOGGER.error("Failed to retrieve supporter form resource", e);
return Collections.emptyList();
}
if (inputStream != null) {
try {
return Optional.of(GSON.<Supporter.OldList>fromJson(new JsonReader(new InputStreamReader(inputStream)), TypeToken.get(Supporter.OldList.class).getType()).toNew());
} catch (JsonSyntaxException ex) {
LOGGER.error("Failed to retrieve supporter from file", ex);
}
}
}
return file;
return Optional.ofNullable(file);
}

}
14 changes: 8 additions & 6 deletions src/main/java/de/teamlapen/vampirism/util/SupporterManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -48,12 +48,14 @@ public static Supporter getRandomVampire(@NotNull RandomSource rnd) {
}

public static void init() {
VampirismAPI.settings().getSupportersAsync().thenAccept(supporters -> {
var supporter = new Supporter[2][];
supporter[0] = supporters.stream().filter(s -> s.faction().equals(REFERENCE.VAMPIRE_PLAYER_KEY)).toArray(Supporter[]::new);
supporter[1] = supporters.stream().filter(s -> s.faction().equals(REFERENCE.HUNTER_PLAYER_KEY)).toArray(Supporter[]::new);
SupporterManager.supporters = supporter;
LOGGER.trace("Supporters {}", getDebugString());
VampirismAPI.settings().getSupportersAsync().thenAccept(optional -> {
optional.ifPresentOrElse(supporters -> {
var supporter = new Supporter[2][];
supporter[0] = supporters.stream().filter(s -> s.faction().equals(REFERENCE.VAMPIRE_PLAYER_KEY)).toArray(Supporter[]::new);
supporter[1] = supporters.stream().filter(s -> s.faction().equals(REFERENCE.HUNTER_PLAYER_KEY)).toArray(Supporter[]::new);
SupporterManager.supporters = supporter;
LOGGER.trace("Supporters {}", getDebugString());
}, () -> LOGGER.warn("Failed to retrieve supporters"));
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public static void execute() {
private static void send() {
try {
URIBuilder builder = new URIBuilder(REFERENCE.SETTINGS_API);
addPathSegment(builder, REFERENCE.SETTINGS_API_VERSION, "telemetry", "basic");
addPathSegment(builder,"telemetry", "basic");
builder.addParameter("mod_version", REFERENCE.VERSION.toString());
builder.addParameter("mc_version", MCPVersion.getMCVersion());
builder.addParameter("mod_count", Integer.toString(ModList.get().size()));
Expand Down
File renamed without changes.

0 comments on commit 7661995

Please sign in to comment.