diff --git a/.github/workflows/update_api.yml b/.github/workflows/update_api.yml new file mode 100644 index 0000000000..46fe6936c5 --- /dev/null +++ b/.github/workflows/update_api.yml @@ -0,0 +1,25 @@ +name: Update API + +on: + push: + branches: + - ${{ github.event.repository.default_branch }} + paths: + - 'src/main/resources/supporters.json' + - 'src/main/resources/default_remote_config.json' + +jobs: + upload: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - name: Upload supporters + uses: wei/curl@v1 + with: + args: | + -X 'POST' 'https://api.vampirism.dev/api/v0/supporter/set' -H 'x-api-key: ${{ secrets.VAMPIRISM_API }}' -H 'Content-Type: application/json' --upload-file src/main/resources/supporters.json + - name: Upload settings + 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/default_remote_config.json diff --git a/src/api/java/de/teamlapen/vampirism/api/VampirismAPI.java b/src/api/java/de/teamlapen/vampirism/api/VampirismAPI.java index d7aa0f50a6..dfa99a5931 100755 --- a/src/api/java/de/teamlapen/vampirism/api/VampirismAPI.java +++ b/src/api/java/de/teamlapen/vampirism/api/VampirismAPI.java @@ -12,6 +12,7 @@ import de.teamlapen.vampirism.api.entity.player.vampire.IVampirePlayer; import de.teamlapen.vampirism.api.entity.player.vampire.IVampireVisionRegistry; import de.teamlapen.vampirism.api.items.IExtendedBrewingRecipeRegistry; +import de.teamlapen.vampirism.api.settings.ISettingsProvider; import de.teamlapen.vampirism.api.world.IVampirismWorld; import net.minecraft.world.entity.PathfinderMob; import net.minecraft.world.entity.player.Player; @@ -38,6 +39,7 @@ public class VampirismAPI { private static IActionManager actionManager; private static IEntityActionManager entityActionManager; private static IExtendedBrewingRecipeRegistry extendedBrewingRecipeRegistry; + private static ISettingsProvider settings; public static ISkillManager skillManager() { return skillManager; @@ -81,6 +83,10 @@ public static IExtendedBrewingRecipeRegistry extendedBrewingRecipeRegistry() { return extendedBrewingRecipeRegistry; } + public static ISettingsProvider settings() { + return settings; + } + /** * Set up the API registries * FOR INTERNAL USAGE ONLY @@ -89,7 +95,7 @@ public static IExtendedBrewingRecipeRegistry extendedBrewingRecipeRegistry() { */ @ApiStatus.Internal public static void setUpRegistries(IFactionRegistry factionRegistryIn, ISundamageRegistry sundamageRegistryIn, IVampirismEntityRegistry entityRegistryIn, IActionManager actionManagerIn, ISkillManager skillManagerIn, - IVampireVisionRegistry vampireVisionRegistryIn, IEntityActionManager entityActionManagerIn, IExtendedBrewingRecipeRegistry extendedBrewingRecipeRegistryIn) { + IVampireVisionRegistry vampireVisionRegistryIn, IEntityActionManager entityActionManagerIn, IExtendedBrewingRecipeRegistry extendedBrewingRecipeRegistryIn, ISettingsProvider settingsIn) { if (INIT) throw new IllegalStateException("Vampirism API can only be setup once"); factionRegistry = factionRegistryIn; sundamageRegistry = sundamageRegistryIn; @@ -99,6 +105,7 @@ public static void setUpRegistries(IFactionRegistry factionRegistryIn, ISundamag vampireVisionRegistry = vampireVisionRegistryIn; entityActionManager = entityActionManagerIn; extendedBrewingRecipeRegistry = extendedBrewingRecipeRegistryIn; + settings = settingsIn; INIT = true; } @@ -109,7 +116,7 @@ public static void setUpRegistries(IFactionRegistry factionRegistryIn, ISundamag @SuppressWarnings("EmptyMethod") @ApiStatus.Internal public static void onSetupComplete() { - + settings.syncSettingsCache(); } /** diff --git a/src/api/java/de/teamlapen/vampirism/api/settings/ISettingsProvider.java b/src/api/java/de/teamlapen/vampirism/api/settings/ISettingsProvider.java new file mode 100644 index 0000000000..f2b0072f1a --- /dev/null +++ b/src/api/java/de/teamlapen/vampirism/api/settings/ISettingsProvider.java @@ -0,0 +1,39 @@ +package de.teamlapen.vampirism.api.settings; + +import org.jetbrains.annotations.Contract; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Collection; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; + +/** + * Provides access to the settings api at api.vampirism.dev + */ +public interface ISettingsProvider { + + /** + * @param key settings key + * @return true if the settings value exists and the value is {@code true} + */ + @Contract(pure = true) + boolean isSettingTrue(@NotNull String key); + + /** + * @param key settings key + * @return settings value for the given key + */ + @NotNull + @Contract(pure = true) + Optional getSettingsValue(@NotNull String key); + + @NotNull + CompletableFuture>> getSupportersAsync(); + + /** + * updates the cache of the settings + */ + void syncSettingsCache(); + +} diff --git a/src/api/java/de/teamlapen/vampirism/api/settings/Supporter.java b/src/api/java/de/teamlapen/vampirism/api/settings/Supporter.java new file mode 100644 index 0000000000..3292e9d431 --- /dev/null +++ b/src/api/java/de/teamlapen/vampirism/api/settings/Supporter.java @@ -0,0 +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 vampires, @NotNull List hunters) { + public Collection 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()); + } + } +} diff --git a/src/lib/java/de/teamlapen/lib/lib/util/VersionChecker.java b/src/lib/java/de/teamlapen/lib/lib/util/VersionChecker.java index 41738e13df..ca3c173b43 100755 --- a/src/lib/java/de/teamlapen/lib/lib/util/VersionChecker.java +++ b/src/lib/java/de/teamlapen/lib/lib/util/VersionChecker.java @@ -29,6 +29,7 @@ * Uses an update file format which is an extension to forge one's, so you can use the same file for forge, but have additional information here e.g. download link. * Requires a versioning system, which is like Vampirism's */ +@Deprecated public class VersionChecker implements Runnable { private final static Logger LOGGER = LogManager.getLogger(); private static final int MAX_HTTP_REDIRECTS = Integer.getInteger("http.maxRedirects", 20); diff --git a/src/lib/java/de/teamlapen/lib/util/QualifiedVersion.java b/src/lib/java/de/teamlapen/lib/util/QualifiedVersion.java new file mode 100644 index 0000000000..7c31eb8b55 --- /dev/null +++ b/src/lib/java/de/teamlapen/lib/util/QualifiedVersion.java @@ -0,0 +1,50 @@ +package de.teamlapen.lib.util; + +import org.apache.maven.artifact.versioning.DefaultArtifactVersion; + +public class QualifiedVersion extends DefaultArtifactVersion { + + private final TYPE type; + + public QualifiedVersion(String version) { + super(version); + String qualifier = getQualifier(); + TYPE type = TYPE.RELEASE; + if (qualifier != null) { + if (qualifier.contains("alpha")) { + type = TYPE.ALPHA; + } else if (qualifier.contains("beta")) { + type = TYPE.BETA; + } else if (qualifier.contains("test")) { + type = TYPE.TEST; + } else if (qualifier.contains("build")) { + type = TYPE.DEV; + } + } + this.type = type; + } + + public boolean isTestVersion() { + return type == TYPE.TEST; + } + + public boolean isAlphaVersion() { + return type == TYPE.ALPHA; + } + + public boolean isBetaVersion() { + return type == TYPE.BETA; + } + + public boolean isReleaseVersion() { + return type == TYPE.RELEASE; + } + + public boolean isDevVersion() { + return type == TYPE.DEV; + } + + enum TYPE { + RELEASE, BETA, ALPHA, TEST, DEV + } +} diff --git a/src/main/java/de/teamlapen/vampirism/GeneralEventHandler.java b/src/main/java/de/teamlapen/vampirism/GeneralEventHandler.java index 695aa1ca72..d3552e6527 100644 --- a/src/main/java/de/teamlapen/vampirism/GeneralEventHandler.java +++ b/src/main/java/de/teamlapen/vampirism/GeneralEventHandler.java @@ -1,7 +1,6 @@ package de.teamlapen.vampirism; import de.teamlapen.lib.lib.util.UtilLib; -import de.teamlapen.lib.lib.util.VersionChecker; import de.teamlapen.vampirism.api.general.BloodConversionRegistry; import de.teamlapen.vampirism.config.VampirismConfig; import de.teamlapen.vampirism.core.ModLootTables; @@ -48,24 +47,9 @@ public void onAttachCapabilityWorld(@NotNull AttachCapabilitiesEvent even @SubscribeEvent public void onPlayerLoggedIn(PlayerEvent.@NotNull PlayerLoggedInEvent event) { - VersionChecker.VersionInfo versionInfo = VampirismMod.instance.getVersionInfo(); - if (!versionInfo.isChecked()) LOGGER.warn("Version check is not finished yet"); - Player player = event.getEntity(); boolean isAdminLikePlayer = !ServerLifecycleHooks.getCurrentServer().isDedicatedServer() || UtilLib.isPlayerOp(player); - if (VampirismConfig.COMMON.versionCheck.get() && versionInfo.isNewVersionAvailable()) { - if (isAdminLikePlayer || player.getRandom().nextInt(5) == 0) { - if (player.getRandom().nextInt(4) == 0) { - VersionChecker.Version newVersion = versionInfo.getNewVersion(); - player.sendSystemMessage(Component.translatable("text.vampirism.outdated", versionInfo.getCurrentVersion().name, newVersion.name)); - Component download = Component.translatable("text.vampirism.update_message.download").withStyle(style -> style.withClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, newVersion.getUrl() == null ? versionInfo.getHomePage() : newVersion.getUrl())).withUnderlined(true).applyFormat(ChatFormatting.BLUE)); - Component changelog = Component.translatable("text.vampirism.update_message.changelog").withStyle(style -> style.withClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/vampirism changelog")).withUnderlined(true)); - Component modpage = Component.translatable("text.vampirism.update_message.modpage").withStyle(style -> style.withClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, versionInfo.getHomePage())).withUnderlined(true).applyFormat(ChatFormatting.BLUE)); - player.sendSystemMessage(Component.literal("").append(download).append(Component.literal(" ")).append(changelog).append(Component.literal(" ")).append(modpage)); - } - } - } if (isAdminLikePlayer) { //TODO 1.19 // List mods = IntegrationsNotifier.shouldNotifyAboutIntegrations(); diff --git a/src/main/java/de/teamlapen/vampirism/REFERENCE.java b/src/main/java/de/teamlapen/vampirism/REFERENCE.java index 0cd73d04ef..e31379a795 100755 --- a/src/main/java/de/teamlapen/vampirism/REFERENCE.java +++ b/src/main/java/de/teamlapen/vampirism/REFERENCE.java @@ -1,45 +1,47 @@ package de.teamlapen.vampirism; +import de.teamlapen.lib.util.QualifiedVersion; import net.minecraft.resources.ResourceLocation; -import org.apache.maven.artifact.versioning.ArtifactVersion; -import org.apache.maven.artifact.versioning.DefaultArtifactVersion; +import net.minecraftforge.fml.ModList; /** * Class to store constants and stuff */ public class REFERENCE { + // Vampirism public static final String MODID = "vampirism"; public static final String NAME = "Vampirism"; - public static final String MINECRAFT_VERSION = "@MVERSION@"; - public static final String FORGE_VERSION_MIN = "14.23.1.2554"; + public static final String INTEGRATIONS_MODID = "vampirism_integrations"; + public static final QualifiedVersion VERSION = new QualifiedVersion(ModList.get().getModContainerById(MODID).map(s -> s.getModInfo().getVersion().toString()).orElse("1.0.0")); + + // changeable values public static final int HIGHEST_VAMPIRE_LEVEL = 14; public static final int HIGHEST_HUNTER_LEVEL = 14; public static final int HIGHEST_VAMPIRE_LORD = 5; public static final int HIGHEST_HUNTER_LORD = 5; - public static final String FORGE_VERSION = "@FVERSION@"; - public static final String VERSION_UPDATE_FILE = "https://maxanier.de/projects/vampirism/versions.json"; - public static final String SUPPORTER_FILE = "https://maxanier.de/projects/vampirism/supporters.json"; - public static final String CURSEFORGE_LINK = "https://minecraft.curseforge.com/projects/vampirism-become-a-vampire"; - public static final String INTEGRATIONS_MODID = "vampirism_integrations"; - public static final String INTEGRATIONS_LINK = "https://minecraft.curseforge.com/projects/vampirism-integrations"; - public static final String GUIDEAPI_LINK = "https://www.curseforge.com/minecraft/mc-mods/guide-api-village-and-pillage"; public static final int EYE_TYPE_COUNT = 16; public static final int FANG_TYPE_COUNT = 7; /** * Check for vampire garlic damage every n ticks * Must be higher than 1, due to implementation */ - public final static int REFRESH_GARLIC_TICKS = 40; + public static final int REFRESH_GARLIC_TICKS = 40; /** * Check for vampire sun damage every n ticks * Must be higher than 2 due to implementation */ - public final static int REFRESH_SUNDAMAGE_TICKS = 8; - public final static ResourceLocation FACTION_PLAYER_HANDLER_KEY = new ResourceLocation(MODID, "ifactionplayerhandler"); - public final static ResourceLocation VAMPIRE_PLAYER_KEY = new ResourceLocation(MODID, "vampire"); - public final static ResourceLocation HUNTER_PLAYER_KEY = new ResourceLocation(MODID, "hunter"); - public final static ResourceLocation EXTENDED_CREATURE_KEY = new ResourceLocation(MODID, "iextendedcreature"); - public final static ResourceLocation WORLD_CAP_KEY = new ResourceLocation(MODID, "world"); - public static ArtifactVersion VERSION = new DefaultArtifactVersion("0.0.0"); + public static final int REFRESH_SUNDAMAGE_TICKS = 8; + + // links + 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/v1"; + // fixed values + public static final ResourceLocation FACTION_PLAYER_HANDLER_KEY = new ResourceLocation(MODID, "ifactionplayerhandler"); + public static final ResourceLocation VAMPIRE_PLAYER_KEY = new ResourceLocation(MODID, "vampire"); + public static final ResourceLocation HUNTER_PLAYER_KEY = new ResourceLocation(MODID, "hunter"); + public static final ResourceLocation EXTENDED_CREATURE_KEY = new ResourceLocation(MODID, "iextendedcreature"); + public static final ResourceLocation WORLD_CAP_KEY = new ResourceLocation(MODID, "world"); } diff --git a/src/main/java/de/teamlapen/vampirism/VampirismMod.java b/src/main/java/de/teamlapen/vampirism/VampirismMod.java index 8f66f81274..a02fdf0627 100755 --- a/src/main/java/de/teamlapen/vampirism/VampirismMod.java +++ b/src/main/java/de/teamlapen/vampirism/VampirismMod.java @@ -5,7 +5,6 @@ import de.teamlapen.lib.lib.network.AbstractPacketDispatcher; import de.teamlapen.lib.lib.network.ISyncable; import de.teamlapen.lib.lib.util.IInitListener; -import de.teamlapen.lib.lib.util.VersionChecker; import de.teamlapen.lib.util.Color; import de.teamlapen.lib.util.OptifineHandler; import de.teamlapen.vampirism.api.VReference; @@ -43,6 +42,7 @@ import de.teamlapen.vampirism.entity.player.vampire.VampirePlayer; import de.teamlapen.vampirism.items.VampireRefinementItem; import de.teamlapen.vampirism.items.crossbow.CrossbowArrowHandler; +import de.teamlapen.vampirism.misc.SettingsProvider; import de.teamlapen.vampirism.misc.VampirismLogger; import de.teamlapen.vampirism.modcompat.IMCHandler; import de.teamlapen.vampirism.modcompat.terrablender.TerraBlenderCompat; @@ -67,7 +67,6 @@ import net.minecraftforge.event.server.ServerAboutToStartEvent; import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.fml.DistExecutor; -import net.minecraftforge.fml.ModList; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.event.lifecycle.*; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; @@ -94,20 +93,12 @@ public class VampirismMod { public static boolean inDataGen = false; private final @NotNull RegistryManager registryManager = new RegistryManager(); - private VersionChecker.VersionInfo versionInfo; public VampirismMod() { instance = this; checkEnv(); - Optional opt = ModList.get().getModContainerById(REFERENCE.MODID); - if (opt.isPresent()) { - REFERENCE.VERSION = opt.get().getModInfo().getVersion(); - } else { - LOGGER.warn("Cannot get version from mod info"); - } - IEventBus modbus = FMLJavaModLoadingContext.get().getModEventBus(); modbus.addListener(this::setup); @@ -142,11 +133,6 @@ public VampirismMod() { } } - public VersionChecker.VersionInfo getVersionInfo() { - - return versionInfo; - } - public void onAddReloadListenerEvent(@NotNull AddReloadListenerEvent event) { SkillTreeManager.getInstance().getSkillTree().initRootSkills();//Load root skills here, so even if data pack reload fail, the root skills are available #622 event.addListener(SkillTreeManager.getInstance()); @@ -217,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()); + 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() @@ -277,23 +263,18 @@ private void setup(final @NotNull FMLCommonSetupEvent event) { dispatcher.registerPackets(); onInitStep(IInitListener.Step.COMMON_SETUP, event); - if (!VampirismConfig.COMMON.versionCheck.get()) { - versionInfo = new VersionChecker.VersionInfo(REFERENCE.VERSION); - } else { - versionInfo = VersionChecker.executeVersionCheck(REFERENCE.VERSION_UPDATE_FILE, REFERENCE.VERSION, !inDev && VampirismConfig.COMMON.collectStats.get()); - } - MinecraftForge.EVENT_BUS.register(new ModPlayerEventHandler()); MinecraftForge.EVENT_BUS.register(new ModEntityEventHandler()); MinecraftForge.EVENT_BUS.addListener(ModLootTables::onLootLoad); - SupporterManager.getInstance().initAsync(); + SupporterManager.init(); VampireBookManager.getInstance().init(); ModEntitySelectors.registerSelectors(); event.enqueueWork(TerraBlenderCompat::registerBiomeProviderIfPresentUnsafe); // VanillaStructureModifications.addVillageStructures(RegistryAccess.EMPTY); + TelemetryCollector.execute(); } private void setupClient(@NotNull FMLClientSetupEvent event) { diff --git a/src/main/java/de/teamlapen/vampirism/client/gui/screens/skills/SkillsScreen.java b/src/main/java/de/teamlapen/vampirism/client/gui/screens/skills/SkillsScreen.java index ff6cac1a8f..18855276fc 100644 --- a/src/main/java/de/teamlapen/vampirism/client/gui/screens/skills/SkillsScreen.java +++ b/src/main/java/de/teamlapen/vampirism/client/gui/screens/skills/SkillsScreen.java @@ -112,7 +112,7 @@ protected void init() { FactionPlayerHandler.getOpt(minecraft.player).ifPresent(fph -> { fph.getCurrentFactionPlayer().ifPresent(factionPlayer -> { - boolean test = VampirismMod.inDev || VampirismMod.instance.getVersionInfo().getCurrentVersion().isTestVersion(); + boolean test = VampirismMod.inDev || REFERENCE.VERSION.isTestVersion(); resetSkills = this.addRenderableWidget(new ExtendedButton(guiLeft + 85, guiTop + 194, 80, 20, Component.translatable("text.vampirism.skill.resetall"), (context) -> { VampirismMod.dispatcher.sendToServer(new ServerboundSimpleInputEvent(ServerboundSimpleInputEvent.Type.RESET_SKILLS)); diff --git a/src/main/java/de/teamlapen/vampirism/command/VersionCheckCommand.java b/src/main/java/de/teamlapen/vampirism/command/VersionCheckCommand.java deleted file mode 100644 index 24de67c5c2..0000000000 --- a/src/main/java/de/teamlapen/vampirism/command/VersionCheckCommand.java +++ /dev/null @@ -1,50 +0,0 @@ -package de.teamlapen.vampirism.command; - -import com.mojang.brigadier.builder.ArgumentBuilder; -import com.mojang.brigadier.context.CommandContext; -import de.teamlapen.lib.lib.util.BasicCommand; -import de.teamlapen.lib.lib.util.VersionChecker; -import de.teamlapen.vampirism.VampirismMod; -import net.minecraft.ChatFormatting; -import net.minecraft.SharedConstants; -import net.minecraft.commands.CommandSourceStack; -import net.minecraft.commands.Commands; -import net.minecraft.network.chat.ClickEvent; -import net.minecraft.network.chat.Component; -import org.jetbrains.annotations.NotNull; - -import java.util.List; - -public class VersionCheckCommand extends BasicCommand { - - public static ArgumentBuilder register() { - return setup(Commands.literal("checkForUpdate")); - } - - private static ArgumentBuilder setup(@NotNull ArgumentBuilder builder) { - return builder.requires(context -> context.hasPermission(PERMISSION_LEVEL_ALL)) - .executes(VersionCheckCommand::changelog); - } - - private static int changelog(@NotNull CommandContext context) { - if (!VampirismMod.instance.getVersionInfo().isNewVersionAvailable()) { - context.getSource().sendSuccess(() -> Component.translatable("command.vampirism.base.changelog.newversion"), false); - return 0; - } - VersionChecker.Version newVersion = VampirismMod.instance.getVersionInfo().getNewVersion(); - List changes = newVersion.getChanges(); - context.getSource().sendSuccess(() -> Component.literal(ChatFormatting.GREEN + "Vampirism " + newVersion.name + "(" + SharedConstants.getCurrentVersion().getName() + ")"), true); - for (String c : changes) { - context.getSource().sendSuccess(() -> Component.literal("-" + c), false); - } - context.getSource().sendSuccess(() -> Component.literal(""), false); - String homepage = VampirismMod.instance.getVersionInfo().getHomePage(); - - Component download = Component.translatable("text.vampirism.update_message.download").withStyle(style -> style.withClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, newVersion.getUrl() == null ? homepage : newVersion.getUrl())).withUnderlined(true).applyFormat(ChatFormatting.BLUE)); - Component changelog = Component.translatable("text.vampirism.update_message.changelog").withStyle(style -> style.withClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/vampirism checkForUpdate")).withUnderlined(true)); - Component modpage = Component.translatable("text.vampirism.update_message.modpage").withStyle(style -> style.withClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, homepage)).withUnderlined(true).applyFormat(ChatFormatting.BLUE)); - context.getSource().sendSuccess(() -> Component.literal("").append(download).append(Component.literal(" ")).append(changelog).append(Component.literal(" ")).append(modpage), false); - return 1; - } - -} diff --git a/src/main/java/de/teamlapen/vampirism/config/VampirismConfig.java b/src/main/java/de/teamlapen/vampirism/config/VampirismConfig.java index 5cc483848a..65e940d134 100644 --- a/src/main/java/de/teamlapen/vampirism/config/VampirismConfig.java +++ b/src/main/java/de/teamlapen/vampirism/config/VampirismConfig.java @@ -301,7 +301,6 @@ public static class Client { */ public static class Common { - public final ForgeConfigSpec.BooleanValue versionCheck; public final ForgeConfigSpec.BooleanValue collectStats; public final ForgeConfigSpec.ConfigValue integrationsNotifier; public final ForgeConfigSpec.BooleanValue optifineBloodvisionWarning; @@ -327,7 +326,6 @@ public static class Common { Common(ForgeConfigSpec.@NotNull Builder builder) { builder.comment("Common configuration settings. Most other configuration can be found in the world (server)configuration folder") .push("common"); - versionCheck = builder.comment("Check for new versions of Vampirism on startup").define("versionCheck", true); collectStats = builder.comment("Send mod version, MC version and mod count to mod author").define("collectStats", true); builder.push("internal"); diff --git a/src/main/java/de/teamlapen/vampirism/core/ModCommands.java b/src/main/java/de/teamlapen/vampirism/core/ModCommands.java index 26803a4cc6..2d8870568c 100644 --- a/src/main/java/de/teamlapen/vampirism/core/ModCommands.java +++ b/src/main/java/de/teamlapen/vampirism/core/ModCommands.java @@ -50,7 +50,6 @@ public static void registerCommands(@NotNull CommandDispatcherliteral(s) .then(BindActionCommand.register()) - .then(VersionCheckCommand.register()) .then(CurrentDimensionCommand.register()) .then(EyeCommand.register()) .then(FangCommand.register()) diff --git a/src/main/java/de/teamlapen/vampirism/entity/hunter/AdvancedHunterEntity.java b/src/main/java/de/teamlapen/vampirism/entity/hunter/AdvancedHunterEntity.java index 889dbcf85f..d829b58108 100644 --- a/src/main/java/de/teamlapen/vampirism/entity/hunter/AdvancedHunterEntity.java +++ b/src/main/java/de/teamlapen/vampirism/entity/hunter/AdvancedHunterEntity.java @@ -9,6 +9,7 @@ import de.teamlapen.vampirism.api.entity.actions.EntityActionTier; import de.teamlapen.vampirism.api.entity.actions.IEntityActionUser; import de.teamlapen.vampirism.api.entity.hunter.IAdvancedHunter; +import de.teamlapen.vampirism.api.settings.Supporter; import de.teamlapen.vampirism.api.world.ICaptureAttributes; import de.teamlapen.vampirism.config.BalanceMobProps; import de.teamlapen.vampirism.core.ModEntities; @@ -318,12 +319,12 @@ protected void defineSynchedData() { @Nullable @Override public SpawnGroupData finalizeSpawn(ServerLevelAccessor pLevel, DifficultyInstance pDifficulty, MobSpawnType pReason, @Nullable SpawnGroupData pSpawnData, @Nullable CompoundTag pDataTag) { - SupporterManager.Supporter supporter = SupporterManager.getInstance().getRandomHunter(random); + Supporter supporter = SupporterManager.getRandomHunter(random); this.getEntityData().set(TYPE, supporter.typeId()); this.getEntityData().set(TYPE, supporter.typeId()); - this.getEntityData().set(NAME, supporter.senderName() == null ? "none" : supporter.senderName()); - this.getEntityData().set(TEXTURE, supporter.textureName() == null ? "none" : supporter.textureName()); - this.lootBookId = supporter.bookID(); + this.getEntityData().set(NAME, supporter.name()); + this.getEntityData().set(TEXTURE, supporter.texture()); + this.lootBookId = supporter.bookId(); return super.finalizeSpawn(pLevel, pDifficulty, pReason, pSpawnData, pDataTag); } diff --git a/src/main/java/de/teamlapen/vampirism/entity/vampire/AdvancedVampireEntity.java b/src/main/java/de/teamlapen/vampirism/entity/vampire/AdvancedVampireEntity.java index 670932bfa8..6078ae4c8d 100644 --- a/src/main/java/de/teamlapen/vampirism/entity/vampire/AdvancedVampireEntity.java +++ b/src/main/java/de/teamlapen/vampirism/entity/vampire/AdvancedVampireEntity.java @@ -9,6 +9,7 @@ import de.teamlapen.vampirism.api.entity.actions.EntityActionTier; import de.teamlapen.vampirism.api.entity.actions.IEntityActionUser; import de.teamlapen.vampirism.api.entity.vampire.IAdvancedVampire; +import de.teamlapen.vampirism.api.settings.Supporter; import de.teamlapen.vampirism.api.world.ICaptureAttributes; import de.teamlapen.vampirism.config.BalanceMobProps; import de.teamlapen.vampirism.core.ModEffects; @@ -337,11 +338,11 @@ protected void defineSynchedData() { @Nullable @Override public SpawnGroupData finalizeSpawn(ServerLevelAccessor pLevel, DifficultyInstance pDifficulty, MobSpawnType pReason, @Nullable SpawnGroupData pSpawnData, @Nullable CompoundTag pDataTag) { - SupporterManager.Supporter supporter = SupporterManager.getInstance().getRandomVampire(random); - lootBookId = supporter.bookID(); + Supporter supporter = SupporterManager.getRandomVampire(random); + lootBookId = supporter.bookId(); this.getEntityData().set(TYPE, supporter.typeId()); - this.getEntityData().set(NAME, supporter.senderName() == null ? "none" : supporter.senderName()); - this.getEntityData().set(TEXTURE, supporter.textureName() == null ? "none" : supporter.textureName()); + this.getEntityData().set(NAME, supporter.name()); + this.getEntityData().set(TEXTURE, supporter.texture()); return super.finalizeSpawn(pLevel, pDifficulty, pReason, pSpawnData, pDataTag); } diff --git a/src/main/java/de/teamlapen/vampirism/items/HunterHatItem.java b/src/main/java/de/teamlapen/vampirism/items/HunterHatItem.java index ede3905d5a..c5d8a0458d 100644 --- a/src/main/java/de/teamlapen/vampirism/items/HunterHatItem.java +++ b/src/main/java/de/teamlapen/vampirism/items/HunterHatItem.java @@ -1,6 +1,7 @@ package de.teamlapen.vampirism.items; import de.teamlapen.lib.lib.util.UtilLib; +import de.teamlapen.vampirism.api.VampirismAPI; import de.teamlapen.vampirism.client.model.armor.HunterHatModel; import de.teamlapen.vampirism.util.RegUtil; import net.minecraft.client.model.HumanoidModel; @@ -63,10 +64,10 @@ protected String getOrCreateDescriptionId() { @Override public void onArmorTick(ItemStack stack, Level world, Player player) { - if(stack.hasCustomHoverName() && "10000000".equals(stack.getHoverName().getString())){ + if (stack.hasCustomHoverName() && "10000000".equals(stack.getHoverName().getString()) && VampirismAPI.settings().isSettingTrue("vampirism:10000000d")) { UtilLib.spawnParticlesAroundEntity(player, ParticleTypes.ELECTRIC_SPARK, 0.5, 4); - if(player.tickCount % 16 == 4) { - player.addEffect(new MobEffectInstance(MobEffects.LEVITATION,30,0)); + if (player.tickCount % 16 == 4) { + player.addEffect(new MobEffectInstance(MobEffects.LEVITATION, 30, 0)); player.addEffect(new MobEffectInstance(MobEffects.SLOW_FALLING, 100, 2)); } } diff --git a/src/main/java/de/teamlapen/vampirism/items/OblivionItem.java b/src/main/java/de/teamlapen/vampirism/items/OblivionItem.java index 86c8684efb..d31497b463 100644 --- a/src/main/java/de/teamlapen/vampirism/items/OblivionItem.java +++ b/src/main/java/de/teamlapen/vampirism/items/OblivionItem.java @@ -2,6 +2,7 @@ import de.teamlapen.lib.HelperLib; import de.teamlapen.lib.lib.network.ISyncable; +import de.teamlapen.vampirism.REFERENCE; import de.teamlapen.vampirism.VampirismMod; import de.teamlapen.vampirism.api.entity.player.IFactionPlayer; import de.teamlapen.vampirism.api.entity.player.skills.ISkillHandler; @@ -21,6 +22,7 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import java.nio.file.ReadOnlyFileSystemException; import java.util.Arrays; import java.util.List; import java.util.Optional; @@ -34,7 +36,7 @@ public static void applyEffect(@NotNull IFactionPlayer factionPlayer) { if (((SkillHandler) skillHandler).getRootNodes().stream().flatMap(a -> a.getChildren().stream()).flatMap(a -> Arrays.stream(a.getElements())).noneMatch(skillHandler::isSkillEnabled)) { return; } - boolean test = VampirismMod.inDev || VampirismMod.instance.getVersionInfo().getCurrentVersion().isTestVersion(); + boolean test = VampirismMod.inDev || REFERENCE.VERSION.isTestVersion(); player.addEffect(new MobEffectInstance(ModEffects.OBLIVION.get(), Integer.MAX_VALUE, test ? 100 : 4)); if (factionPlayer instanceof ISyncable.ISyncableEntityCapabilityInst) { HelperLib.sync((ISyncable.ISyncableEntityCapabilityInst) factionPlayer, factionPlayer.getRepresentingPlayer(), false); diff --git a/src/main/java/de/teamlapen/vampirism/items/VampireClothingItem.java b/src/main/java/de/teamlapen/vampirism/items/VampireClothingItem.java index 1e7a73034a..3ec5a5adf3 100644 --- a/src/main/java/de/teamlapen/vampirism/items/VampireClothingItem.java +++ b/src/main/java/de/teamlapen/vampirism/items/VampireClothingItem.java @@ -4,6 +4,7 @@ import de.teamlapen.vampirism.REFERENCE; import de.teamlapen.vampirism.VampirismMod; import de.teamlapen.vampirism.api.VReference; +import de.teamlapen.vampirism.api.VampirismAPI; import de.teamlapen.vampirism.api.entity.factions.IFaction; import de.teamlapen.vampirism.api.items.IFactionExclusiveItem; import de.teamlapen.vampirism.client.model.armor.*; @@ -95,10 +96,10 @@ public void onArmorTick(ItemStack stack, Level world, @NotNull Player player) { player.addEffect(new MobEffectInstance(ModEffects.POISON.get(), 20, 1)); } } - if(stack.getItem() == ModItems.VAMPIRE_CLOTHING_CROWN.get() && stack.hasCustomHoverName() && "10000000".equals(stack.getHoverName().getString())){ + if (stack.getItem() == ModItems.VAMPIRE_CLOTHING_CROWN.get() && stack.hasCustomHoverName() && "10000000".equals(stack.getHoverName().getString()) && VampirismAPI.settings().isSettingTrue("vampirism:10000000d")) { UtilLib.spawnParticlesAroundEntity(player, ParticleTypes.ELECTRIC_SPARK, 0.5, 4); - if(player.tickCount % 16 == 4) { - player.addEffect(new MobEffectInstance(MobEffects.LEVITATION,30,0)); + if (player.tickCount % 16 == 4) { + player.addEffect(new MobEffectInstance(MobEffects.LEVITATION, 30, 0)); player.addEffect(new MobEffectInstance(MobEffects.SLOW_FALLING, 100, 2)); } } diff --git a/src/main/java/de/teamlapen/vampirism/misc/SettingsProvider.java b/src/main/java/de/teamlapen/vampirism/misc/SettingsProvider.java new file mode 100644 index 0000000000..1270b803f5 --- /dev/null +++ b/src/main/java/de/teamlapen/vampirism/misc/SettingsProvider.java @@ -0,0 +1,136 @@ +package de.teamlapen.vampirism.misc; + +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; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.io.InputStream; +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 { + + private static final Logger LOGGER = LogManager.getLogger(); + private static final Gson GSON = new GsonBuilder().registerTypeHierarchyAdapter(ResourceLocation.class, new ResourceLocationTypeAdapter()).create(); + + private final HttpClient client; + private final String baseUrl; + private final Map settingValues = new HashMap<>(); + + public SettingsProvider(String baseUrl) { + this.baseUrl = baseUrl; + this.client = HttpClient.newHttpClient(); + } + + @Override + public void syncSettingsCache() { + retrieveSettingValuesAsync().handleAsync(this::checkSettings).thenAccept(newValues -> { + this.settingValues.clear(); + newValues.ifPresent(this.settingValues::putAll); + }); + } + + @Override + public @NotNull Optional getSettingsValue(@NotNull String key) { + return Optional.ofNullable(this.settingValues.get(key)); + } + + @Override + public boolean isSettingTrue(@NotNull String key) { + return "true".equals(this.settingValues.get(key)); + } + + @Override + public @NotNull CompletableFuture>> getSupportersAsync() { + return retrieveSupportersAsync().handleAsync(this::checkSupporter); + } + + @Nullable + public CompletableFuture getSettingValueAsync(String key) { + return get("config/get?configId=" + key); + } + + public CompletableFuture> retrieveSettingValuesAsync() { + return get("config/list").thenApply(x -> GSON.fromJson(x, TypeToken.getParameterized(Map.class, String.class, String.class).getType())); + } + + public CompletableFuture> 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> retrieveSupportersAsync() { + return get("supporter/list").thenApply(x -> GSON.fromJson(x, TypeToken.getParameterized(List.class, Supporter.class).getType())); + } + + public CompletableFuture> retrieveSupportersAsync(String modid) { + return retrieveSupportersAsync().thenApply(x -> x.stream().filter(y -> y.faction().getNamespace().equals(modid)).collect(Collectors.toList())); + } + + private CompletableFuture get(String path) { + try { + 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 Optional> checkSettings(Map settings, Throwable error) { + if (error != null) { + LOGGER.error("Failed to retrieve settings from server", error); + } + 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 Optional.ofNullable(settings); + } + + private Optional> checkSupporter(Collection file, Throwable error) { + if (error != null) { + LOGGER.error("Failed to retrieve supporter from server", error); + } + if (false) { + InputStream inputStream = VampirismMod.class.getResourceAsStream("/supporters.json"); + if (inputStream != null) { + try { + return Optional.of(GSON.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 Optional.ofNullable(file); + } + +} diff --git a/src/main/java/de/teamlapen/vampirism/util/SupporterManager.java b/src/main/java/de/teamlapen/vampirism/util/SupporterManager.java index e128b4c798..a9c3b7d22b 100755 --- a/src/main/java/de/teamlapen/vampirism/util/SupporterManager.java +++ b/src/main/java/de/teamlapen/vampirism/util/SupporterManager.java @@ -1,19 +1,13 @@ package de.teamlapen.vampirism.util; -import com.google.common.io.ByteStreams; -import com.google.gson.*; import de.teamlapen.vampirism.REFERENCE; -import de.teamlapen.vampirism.VampirismMod; +import de.teamlapen.vampirism.api.VampirismAPI; +import de.teamlapen.vampirism.api.settings.Supporter; import net.minecraft.util.RandomSource; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import java.io.IOException; -import java.io.InputStream; -import java.net.ConnectException; -import java.net.URL; import java.util.Arrays; /** @@ -25,143 +19,43 @@ public class SupporterManager { private final static Logger LOGGER = LogManager.getLogger(); - private static final SupporterManager instance = new SupporterManager(); + private static Supporter[][] supporters = new Supporter[2][0]; - public static SupporterManager getInstance() { - return instance; - } - - private Supporter[][] supporters; - - private SupporterManager() { - supporters = new Supporter[2][0]; - - } /** * Returns a randomly picked hunter */ - public Supporter getRandomHunter(@NotNull RandomSource rnd) { + public static Supporter getRandomHunter(@NotNull RandomSource rnd) { if (supporters[1].length > 0) { return supporters[1][rnd.nextInt(supporters[1].length)]; } - return new Supporter(null, null, 0, null); + return new Supporter(REFERENCE.HUNTER_PLAYER_KEY, "none", "none", 0, null); } /** * Returns a randomly picked vampire */ - public Supporter getRandomVampire(@NotNull RandomSource rnd) { + public static Supporter getRandomVampire(@NotNull RandomSource rnd) { if (supporters[0].length > 0) { return supporters[0][rnd.nextInt(supporters[0].length)]; } - return new Supporter(null, null, 0, null); + return new Supporter(REFERENCE.VAMPIRE_PLAYER_KEY, "none", "none", 0, null); } - public void initAsync() { - Thread thread = new Thread(REFERENCE.MODID + ":" + "SupporterManager") { - - public void run() { - init(); - } - }; - thread.setDaemon(true); - thread.start(); - } - private @NotNull String getDebugString() { + private static @NotNull String getDebugString() { return "Vampires: " + Arrays.toString(supporters[0]) + " Hunters: " + Arrays.toString(supporters[1]); } - private void init() { - Supporter[][] supporters = null; - InputStream inputStream = null; - try { - inputStream = new URL(REFERENCE.SUPPORTER_FILE).openStream(); - String data = new String(ByteStreams.toByteArray(inputStream)); - - inputStream.close(); - supporters = retrieveSupporter(data); - } catch (IOException e) { - if (e instanceof ConnectException) { - LOGGER.error("Failed to connect to supporter url {}", REFERENCE.SUPPORTER_FILE); - } else { - LOGGER.error("Failed to retrieve supporters from url", e); - } - } - if (supporters == null || VampirismMod.inDev) { - try { - inputStream = VampirismMod.class.getResourceAsStream("/supporters.json"); - String data = new String(ByteStreams.toByteArray(inputStream)); - - inputStream.close(); - supporters = retrieveSupporter(data); - } catch (IOException e) { - LOGGER.error("Failed to retrieve supporters from resources", e); - } - } - if (supporters != null) { - this.supporters = supporters; - LOGGER.trace("Supporters {}", getDebugString()); - } - } - - private @NotNull Supporter parseSupporter(@NotNull JsonObject object) { - String name = null; - String texture = null; - String bookId = null; - int type = 0; - if (object.has("name")) { - name = object.get("name").getAsString(); - } - if (object.has("texture")) { - texture = object.get("texture").getAsString(); - } - if (object.has("type")) { - type = object.get("type").getAsInt(); - } - if (object.has("bookId")) { - bookId = object.get("bookId").getAsString(); - } - return new Supporter(name, texture, type, bookId); - } - - private - @Nullable - Supporter[] @Nullable [] retrieveSupporter(@NotNull String data) { - - try { - Supporter[][] supporters = new Supporter[2][]; - JsonElement main = new JsonParser().parse(data); - JsonArray vampires = main.getAsJsonObject().getAsJsonArray("vampires"); - supporters[0] = new Supporter[vampires.size()]; - for (int i = 0; i < supporters[0].length; i++) { - supporters[0][i] = parseSupporter(vampires.get(i).getAsJsonObject()); - } - JsonArray hunters = main.getAsJsonObject().getAsJsonArray("hunters"); - supporters[1] = new Supporter[hunters.size()]; - for (int i = 0; i < supporters[1].length; i++) { - supporters[1][i] = parseSupporter(hunters.get(i).getAsJsonObject()); - } - return supporters; - } catch (JsonSyntaxException e) { - LOGGER.error("Failed to parse supporter list", e); - } - return null; - - } - - public record Supporter(@Nullable String senderName, @Nullable String textureName, int typeId, - @Nullable String bookID) { - public Supporter(@Nullable String senderName, @Nullable String textureName, int typeId, @Nullable String bookID) { - this.typeId = typeId; - if (senderName != null && senderName.equals("null")) { - this.senderName = null; - } else { - this.senderName = senderName; - } - this.textureName = textureName; - this.bookID = bookID; - } + public static void init() { + 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")); + }); } } diff --git a/src/main/java/de/teamlapen/vampirism/util/TelemetryCollector.java b/src/main/java/de/teamlapen/vampirism/util/TelemetryCollector.java new file mode 100644 index 0000000000..36adfe8f9a --- /dev/null +++ b/src/main/java/de/teamlapen/vampirism/util/TelemetryCollector.java @@ -0,0 +1,59 @@ +package de.teamlapen.vampirism.util; + +import de.teamlapen.vampirism.REFERENCE; +import de.teamlapen.vampirism.config.VampirismConfig; +import net.minecraft.client.Minecraft; +import net.minecraftforge.fml.LogicalSide; +import net.minecraftforge.fml.ModList; +import net.minecraftforge.fml.util.thread.EffectiveSide; +import net.minecraftforge.versions.mcp.MCPVersion; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.utils.URIBuilder; +import org.apache.http.client.utils.URLEncodedUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.io.IOException; +import java.net.HttpCookie; +import java.net.HttpURLConnection; +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.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class TelemetryCollector { + + public static final Logger LOGGER = LogManager.getLogger(); + + public static void execute() { + if (Minecraft.getInstance().allowsTelemetry() && VampirismConfig.COMMON.collectStats.get()) { + send(); + } + } + + private static void send() { + try { + URIBuilder builder = new URIBuilder(REFERENCE.SETTINGS_API); + 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())); + builder.addParameter("side", (EffectiveSide.get() == LogicalSide.CLIENT ? "client" : "server")); + HttpClient.newHttpClient().send(HttpRequest.newBuilder().uri(builder.build()).build(), HttpResponse.BodyHandlers.ofString()); + } catch (URISyntaxException | IOException | InterruptedException e) { + LOGGER.error("Failed to send telemetry data", e); + } + } + + private static void addPathSegment(URIBuilder builder, @SuppressWarnings("SameParameterValue") String... segments) { + List pathSegments = builder.getPathSegments(); + pathSegments.removeIf(String::isBlank); + pathSegments.addAll(Arrays.stream(segments).toList()); + builder.setPathSegments(pathSegments); + } +} diff --git a/src/main/resources/META-INF/mods.toml b/src/main/resources/META-INF/mods.toml index 2189a78e7f..4b7dbccccb 100755 --- a/src/main/resources/META-INF/mods.toml +++ b/src/main/resources/META-INF/mods.toml @@ -39,7 +39,7 @@ license = "${mod_license}" description='''${mod_description}''' displayURL="${mod_url}" logoFile="logo.png" - updateJSONURL="https://maxanier.de/projects/vampirism/versions.json" + updateJSONURL="https://api.modrinth.com/updates/vampirism/forge_updates.json" [[dependencies.${mod_id}]] modId="forge" mandatory=true diff --git a/src/main/resources/default_remote_config.json b/src/main/resources/default_remote_config.json new file mode 100644 index 0000000000..da17bbf8d1 --- /dev/null +++ b/src/main/resources/default_remote_config.json @@ -0,0 +1,3 @@ +{ + "vampirism:10000000d": "true" +} \ No newline at end of file