diff options
author | Gravy Boat <thatgravyboat@gmail.com> | 2021-09-23 23:12:01 -0230 |
---|---|---|
committer | Gravy Boat <thatgravyboat@gmail.com> | 2021-09-23 23:12:01 -0230 |
commit | cd58f0b8fadefdb0026347649bb78b93274e4194 (patch) | |
tree | 770f69401443b9ee94a62f538c179b1bba769ce1 | |
parent | 066111e24e26249522f74340d3b9c6bd6a778dea (diff) | |
download | RewardClaim-cd58f0b8fadefdb0026347649bb78b93274e4194.tar.gz RewardClaim-cd58f0b8fadefdb0026347649bb78b93274e4194.tar.bz2 RewardClaim-cd58f0b8fadefdb0026347649bb78b93274e4194.zip |
Clean up, Moved to kotlin regex, changed to using data class instead of using JsonObjects, updated the image system to be better for housing images, and switched to using essential kotlin language adapter instead of my own.
16 files changed, 249 insertions, 220 deletions
diff --git a/src/main/kotlin/tech/thatgravyboat/rewardclaim/RewardClaim.kt b/src/main/kotlin/tech/thatgravyboat/rewardclaim/RewardClaim.kt index 29628ae..5656692 100644 --- a/src/main/kotlin/tech/thatgravyboat/rewardclaim/RewardClaim.kt +++ b/src/main/kotlin/tech/thatgravyboat/rewardclaim/RewardClaim.kt @@ -11,7 +11,12 @@ import net.minecraftforge.fml.common.event.FMLPreInitializationEvent import net.minecraftforge.fml.common.eventhandler.SubscribeEvent import tech.thatgravyboat.rewardclaim.ui.RewardClaimGui -@Mod(name = "RewardClaim", modid = "gravyrewardclaim", version = "1.0.0", modLanguageAdapter = "tech.thatgravyboat.rewardclaim.adapter.KotlinLanguageAdapter") +@Mod( + name = "RewardClaim", + modid = "gravyrewardclaim", + version = "1.0.0", + modLanguageAdapter = "gg.essential.api.utils.KotlinAdapter" +) object ForgeTemplate { private var rewardClaimTime: Long = 0 @@ -28,26 +33,25 @@ object ForgeTemplate { @SubscribeEvent fun onChatMessage(event: ClientChatReceivedEvent) { - val rewardMatcher = RewardConfiguration.rewardMessageRegex.matcher(event.message.unformattedText.trim()) - val rewardMissedMatcher = RewardConfiguration.rewardMissedMessageRegex.matcher(event.message.unformattedText.trim()) - - if (rewardMatcher.matches()) { - EssentialAPI.getGuiUtil().openScreen(RewardClaimGui(rewardMatcher.group("id"))) + RewardConfiguration.rewardMessageRegex.matchEntire(event.message.unformattedText.trim())?.apply { + EssentialAPI.getGuiUtil().openScreen(RewardClaimGui(groups["id"]!!.value)) rewardClaimTime = System.currentTimeMillis() } - if (rewardMissedMatcher.matches()) { + + RewardConfiguration.rewardMissedMessageRegex.matchEntire(event.message.unformattedText.trim())?.apply { EssentialAPI.getNotifications().push( - "Reward Claim Missed!", - "You missed a reward claim, click on this to open the reward claim gui to claim your reward.", - { EssentialAPI.getGuiUtil().openScreen(RewardClaimGui(rewardMissedMatcher.group("id"))) } - ) + "Reward Claim Missed!", + "You missed a reward claim, click on this to open the reward claim gui to claim your reward." + ) { EssentialAPI.getGuiUtil().openScreen(RewardClaimGui(groups["id"]!!.value)) } event.isCanceled = true } } @SubscribeEvent fun onScreen(event: GuiOpenEvent) { - if (EssentialAPI.getGuiUtil().openedScreen() is RewardClaimGui && event.gui is GuiScreenBook && System.currentTimeMillis() - rewardClaimTime <= 3000){ + if (EssentialAPI.getGuiUtil() + .openedScreen() is RewardClaimGui && event.gui is GuiScreenBook && System.currentTimeMillis() - rewardClaimTime <= 3000 + ) { event.isCanceled = true rewardClaimTime = 0 } diff --git a/src/main/kotlin/tech/thatgravyboat/rewardclaim/RewardConfiguration.kt b/src/main/kotlin/tech/thatgravyboat/rewardclaim/RewardConfiguration.kt index 3d8a79a..01e2af1 100644 --- a/src/main/kotlin/tech/thatgravyboat/rewardclaim/RewardConfiguration.kt +++ b/src/main/kotlin/tech/thatgravyboat/rewardclaim/RewardConfiguration.kt @@ -1,41 +1,38 @@ package tech.thatgravyboat.rewardclaim import com.google.gson.Gson -import com.google.gson.JsonObject -import net.minecraft.util.JsonUtils +import tech.thatgravyboat.rewardclaim.types.ImageType import tech.thatgravyboat.rewardclaim.types.RewardImage import java.io.IOException import java.net.URL import java.util.* -import java.util.regex.Pattern +import kotlin.collections.HashMap private val GSON = Gson() +private val DEFAULT_IMAGE_TYPE = ImageType(142, 100, false) object RewardConfiguration { - val TEXTURES: MutableMap<String, RewardImage> = HashMap<String, RewardImage>() - var rewardMessageRegex: Pattern = Pattern.compile("Click the link to visit our website and claim your reward: https://rewards\\.hypixel\\.net/claim-reward/(?<id>[A-Za-z0-9]{8})") - var rewardMissedMessageRegex: Pattern = Pattern.compile("We noticed you haven't claimed your free Daily Reward yet!\\nTo choose your reward you have to click the link to visit our website! As a reminder, here's your link for today: https://rewards\\.hypixel\\.net/claim-reward/(?<id>[A-Za-z0-9]{8})") - var userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.54 Safari/537.36" + private lateinit var imageTypes: HashMap<String, ImageType> + lateinit var textures: HashMap<String, RewardImage> + lateinit var rewardMessageRegex: Regex + lateinit var rewardMissedMessageRegex: Regex + lateinit var userAgent: String - fun loadData() { - val json = GSON.fromJson(readData(), JsonObject::class.java) - - json.get("textures")?.apply { - for (texture in asJsonArray) { - val image = texture.asJsonObject - TEXTURES[image["id"].asString] = RewardImage(image["url"].asString, JsonUtils.getInt(image, "height", 142)) - } - } + fun getImageType(type: String?) = if (type == null) DEFAULT_IMAGE_TYPE else imageTypes.getOrDefault(type, DEFAULT_IMAGE_TYPE) - json.get("rewardRegex")?.apply { rewardMessageRegex = Pattern.compile(asString) } - json.get("missedRewardRegex")?.apply { rewardMissedMessageRegex = Pattern.compile(asString) } - json.get("userAgent")?.apply { userAgent = asString } + fun loadData() { + val config = GSON.fromJson(readData(), JsonConfig::class.java) + textures = config.textures + imageTypes = config.imageTypes + rewardMessageRegex = Regex(config.rewardRegex) + rewardMissedMessageRegex = Regex(config.missedRewardRegex) + userAgent = config.userAgent } private fun readData(): String { try { Scanner( - URL("https://gist.githubusercontent.com/ThatGravyBoat/05cf118ea1daced936f040a41a648819/raw/2410c868444b073fd212fbed1da5a063d79dc816/data.json").openStream(), + URL("https://raw.githubusercontent.com/ThatGravyBoat/RewardClaim/master/data.json").openStream(), "UTF-8" ).use { scanner -> scanner.useDelimiter("\\A") @@ -46,4 +43,12 @@ object RewardConfiguration { } return "" } + + private data class JsonConfig( + val imageTypes: HashMap<String, ImageType> = hashMapOf(), + val textures: HashMap<String, RewardImage> = hashMapOf(), + val rewardRegex: String = "Click the link to visit our website and claim your reward: https://rewards\\.hypixel\\.net/claim-reward/(?<id>[A-Za-z0-9]{8})", + val missedRewardRegex: String = "We noticed you haven't claimed your free Daily Reward yet!\\nTo choose your reward you have to click the link to visit our website! As a reminder, here's your link for today: https://rewards\\.hypixel\\.net/claim-reward/(?<id>[A-Za-z0-9]{8})", + val userAgent: String = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.54 Safari/537.36" + ) }
\ No newline at end of file diff --git a/src/main/kotlin/tech/thatgravyboat/rewardclaim/RewardLanguage.kt b/src/main/kotlin/tech/thatgravyboat/rewardclaim/RewardLanguage.kt index 6361bc5..8a9ab36 100644 --- a/src/main/kotlin/tech/thatgravyboat/rewardclaim/RewardLanguage.kt +++ b/src/main/kotlin/tech/thatgravyboat/rewardclaim/RewardLanguage.kt @@ -1,8 +1,6 @@ package tech.thatgravyboat.rewardclaim -import java.util.regex.Pattern - -private val TRANSLATION_LINE_REGEX = Pattern.compile("\"(?<key>.*)\": ?\"(?<text>.*)\",?") +private val TRANSLATION_LINE_REGEX = Regex("\"(?<key>.*)\": ?\"(?<text>.*)\",?") class RewardLanguage(translationDataFromHtml: String) { @@ -13,8 +11,8 @@ class RewardLanguage(translationDataFromHtml: String) { //We have to do it this way as this is easier than fixing all the things that isn't //valid in normal json but is valid in javascript objects. Such as escaped single quotes and trailing commas. init { - TRANSLATION_LINE_REGEX.matcher(translationDataFromHtml.replace("\\'", "'")).apply { - while (find()) translations[group("key")] = group("text") + TRANSLATION_LINE_REGEX.findAll(translationDataFromHtml.replace("\\'", "'")).apply { + this.forEach { translations[it.groups["key"]!!.value] = it.groups["text"]!!.value } } } }
\ No newline at end of file diff --git a/src/main/kotlin/tech/thatgravyboat/rewardclaim/adapter/KotlinLanguageAdapter.kt b/src/main/kotlin/tech/thatgravyboat/rewardclaim/adapter/KotlinLanguageAdapter.kt deleted file mode 100644 index 11b3188..0000000 --- a/src/main/kotlin/tech/thatgravyboat/rewardclaim/adapter/KotlinLanguageAdapter.kt +++ /dev/null @@ -1,27 +0,0 @@ -package tech.thatgravyboat.rewardclaim.adapter - -import net.minecraftforge.fml.common.FMLModContainer -import net.minecraftforge.fml.common.ILanguageAdapter -import net.minecraftforge.fml.common.ModContainer -import net.minecraftforge.fml.relauncher.Side -import java.lang.reflect.Field -import java.lang.reflect.Method - -class KotlinLanguageAdapter : ILanguageAdapter { - override fun supportsStatics() = false - - override fun setProxy(target: Field, proxyTarget: Class<*>, proxy: Any) { - target.set(proxyTarget.getDeclaredField("INSTANCE").get(null), proxy) - } - - override fun getNewInstance( - container: FMLModContainer, - objectClass: Class<*>, - classLoader: ClassLoader, - factoryMarkedAnnotation: Method? - ): Any { - return objectClass.fields.find { it.name == "INSTANCE" }?.get(null) ?: objectClass.newInstance() - } - - override fun setInternalProxies(mod: ModContainer?, side: Side?, loader: ClassLoader?) {} -}
\ No newline at end of file diff --git a/src/main/kotlin/tech/thatgravyboat/rewardclaim/types/AdData.kt b/src/main/kotlin/tech/thatgravyboat/rewardclaim/types/AdData.kt new file mode 100644 index 0000000..fe3dcb2 --- /dev/null +++ b/src/main/kotlin/tech/thatgravyboat/rewardclaim/types/AdData.kt @@ -0,0 +1,3 @@ +package tech.thatgravyboat.rewardclaim.types + +data class AdData(val link: String, val duration: Int) diff --git a/src/main/kotlin/tech/thatgravyboat/rewardclaim/types/ImageType.kt b/src/main/kotlin/tech/thatgravyboat/rewardclaim/types/ImageType.kt new file mode 100644 index 0000000..85b9b90 --- /dev/null +++ b/src/main/kotlin/tech/thatgravyboat/rewardclaim/types/ImageType.kt @@ -0,0 +1,3 @@ +package tech.thatgravyboat.rewardclaim.types + +data class ImageType(val height: Int, val width: Int, val center: Boolean) diff --git a/src/main/kotlin/tech/thatgravyboat/rewardclaim/types/RewardData.kt b/src/main/kotlin/tech/thatgravyboat/rewardclaim/types/RewardData.kt index cc89422..4695cbf 100644 --- a/src/main/kotlin/tech/thatgravyboat/rewardclaim/types/RewardData.kt +++ b/src/main/kotlin/tech/thatgravyboat/rewardclaim/types/RewardData.kt @@ -1,42 +1,54 @@ package tech.thatgravyboat.rewardclaim.types +import com.google.gson.annotations.SerializedName import tech.thatgravyboat.rewardclaim.RewardConfiguration import tech.thatgravyboat.rewardclaim.RewardLanguage import java.util.* -import java.util.regex.Pattern -private val ARMOR_PIECE_REGEX = Pattern.compile("^[a-z0-9_]+_([a-z]+)$", Pattern.CASE_INSENSITIVE) -private val ARMOR_REGEX = Pattern.compile("_([a-z]+)$", Pattern.CASE_INSENSITIVE) +private val ARMOR_PIECE_REGEX = Regex("^[a-z0-9_]+_([a-z]+)$", RegexOption.IGNORE_CASE) +private val ARMOR_REGEX = Regex("_([a-z]+)$", RegexOption.IGNORE_CASE) -class RewardData(val rarity: RewardRarity, - private val reward : String, - val amount : Int?, - val boxes : Int?, - private val gameMode : GameMode?, - private val rewardPackage : String?, - private val rewardKey : String? - ) { +data class RewardData( + val rarity: RewardRarity, + private val reward: String, + val amount: Int?, + val intlist: Array<Int>?, + private val gameType: GameMode?, + @SerializedName("package") private val rewardPackage: String?, + @SerializedName("key") private val rewardKey: String? +) { fun getDisplayName(language: RewardLanguage): String { rewardPackage?.let { item -> if (reward.equals("housing_package", ignoreCase = true)) { - return "${rarity.color}${language.translate("housing.skull." + item.replace("specialoccasion_reward_card_skull_", ""))}" + return "${rarity.color}${ + language.translate( + "housing.skull." + item.replace( + "specialoccasion_reward_card_skull_", + "" + ) + ) + }" } } rewardKey?.let { key -> if (reward.equals("add_vanity", ignoreCase = true)) { - val pieceMatcher = ARMOR_PIECE_REGEX.matcher(key) - val armorMatcher = ARMOR_REGEX.matcher(key) - if ("suit" in key && pieceMatcher.find() && armorMatcher.find()) { - return "${rarity.color}${language.translate("vanity." + armorMatcher.group(1))} ${language.translate("vanity.armor." + pieceMatcher.group(1))}" + val pieceMatcher = ARMOR_PIECE_REGEX.find(key) + val armorMatcher = ARMOR_REGEX.find(key) + if ("suit" in key && pieceMatcher != null && armorMatcher != null) { + return "${rarity.color}${language.translate("vanity." + armorMatcher.groups[1]!!.value)} ${ + language.translate( + "vanity.armor." + pieceMatcher.groups[1]!!.value + ) + }" } else if ("emote" in key || "taunt" in key) { return "${rarity.color}${language.translate("vanity.$key")}" } } } return if (reward.equals("tokens", ignoreCase = true) || reward.equals("coins", ignoreCase = true)) { - "${rarity.color}${language.translate("type.$reward").replace("{\$game}", gameMode!!.displayName)}" + "${rarity.color}${language.translate("type.$reward").replace("{\$game}", gameType!!.displayName)}" } else { "${rarity.color}${language.translate("type.$reward")}" } @@ -53,7 +65,9 @@ class RewardData(val rarity: RewardRarity, } } return if (reward.equals("tokens", ignoreCase = true) || reward.equals("coins", ignoreCase = true)) { - "${rarity.color}${language.translate("type.$reward.description").replace("{\$game}", gameMode!!.displayName)}" + "${rarity.color}${ + language.translate("type.$reward.description").replace("{\$game}", gameType!!.displayName) + }" } else { "${rarity.color}${language.translate("type.$reward.description")}" } @@ -74,9 +88,9 @@ class RewardData(val rarity: RewardRarity, rewardPackage?.let { item -> if (id == "housing_package") { val packageId = item.replace("specialoccasion_reward_card_skull_", "") - RewardConfiguration.TEXTURES[id + "_" + packageId]?.let { image -> return image } + RewardConfiguration.textures[id + "_" + packageId]?.let { image -> return image } } } - return RewardConfiguration.TEXTURES[id] + return RewardConfiguration.textures[id] } }
\ No newline at end of file diff --git a/src/main/kotlin/tech/thatgravyboat/rewardclaim/types/RewardImage.kt b/src/main/kotlin/tech/thatgravyboat/rewardclaim/types/RewardImage.kt index fc8446a..d70143b 100644 --- a/src/main/kotlin/tech/thatgravyboat/rewardclaim/types/RewardImage.kt +++ b/src/main/kotlin/tech/thatgravyboat/rewardclaim/types/RewardImage.kt @@ -1,13 +1,14 @@ package tech.thatgravyboat.rewardclaim.types +import com.google.gson.annotations.SerializedName import java.net.MalformedURLException import java.net.URL -class RewardImage(private val urlString: String, val height: Int) { +data class RewardImage(@SerializedName("url") private val urlIn: String, val imageType: String) { val url: URL? get() { return try { - URL(urlString) + URL(urlIn) } catch (ignored: MalformedURLException) { null } diff --git a/src/main/kotlin/tech/thatgravyboat/rewardclaim/types/RewardRarity.kt b/src/main/kotlin/tech/thatgravyboat/rewardclaim/types/RewardRarity.kt index d4e45b1..43cce0c 100644 --- a/src/main/kotlin/tech/thatgravyboat/rewardclaim/types/RewardRarity.kt +++ b/src/main/kotlin/tech/thatgravyboat/rewardclaim/types/RewardRarity.kt @@ -3,6 +3,7 @@ package tech.thatgravyboat.rewardclaim.types import gg.essential.universal.ChatColor import java.awt.Color +@Suppress("unused") enum class RewardRarity(val translationKey: String, val color: ChatColor) { COMMON("rarity.common", ChatColor.WHITE), RARE("rarity.rare", ChatColor.AQUA), diff --git a/src/main/kotlin/tech/thatgravyboat/rewardclaim/types/StreakData.kt b/src/main/kotlin/tech/thatgravyboat/rewardclaim/types/StreakData.kt index 4a5cb98..ef7e6fc 100644 --- a/src/main/kotlin/tech/thatgravyboat/rewardclaim/types/StreakData.kt +++ b/src/main/kotlin/tech/thatgravyboat/rewardclaim/types/StreakData.kt @@ -1,3 +1,3 @@ package tech.thatgravyboat.rewardclaim.types -class StreakData(val progress : Int, val current : Int, val highest : Int)
\ No newline at end of file +data class StreakData(val progress: Int, val current: Int, val highest: Int)
\ No newline at end of file diff --git a/src/main/kotlin/tech/thatgravyboat/rewardclaim/types/WebData.kt b/src/main/kotlin/tech/thatgravyboat/rewardclaim/types/WebData.kt index 38318d1..bdaafe1 100644 --- a/src/main/kotlin/tech/thatgravyboat/rewardclaim/types/WebData.kt +++ b/src/main/kotlin/tech/thatgravyboat/rewardclaim/types/WebData.kt @@ -1,60 +1,40 @@ package tech.thatgravyboat.rewardclaim.types import com.google.gson.Gson -import com.google.gson.JsonObject -import net.minecraft.util.JsonUtils import tech.thatgravyboat.rewardclaim.RewardLanguage -import java.util.regex.Matcher private val GSON = Gson() -class WebData(security : Matcher, data : Matcher, i18n : Matcher) { +class WebData(security: MatchResult, data: MatchResult, i18n: MatchResult) { - val securityToken : String = security.group("token") - val language : RewardLanguage = RewardLanguage(i18n.group("translations")) + val securityToken: String = security.groups["token"]!!.value + val language: RewardLanguage = RewardLanguage(i18n.groups["translations"]!!.value) val rewards = mutableListOf<RewardData>() - var streak : StreakData = StreakData(0,0,0) - var activeAd : Int = 0 - var adLink : String = "https://store.hypixel.net/?utm_source=rewards-video&utm_medium=website&utm_content=TRsCiBNYY7M&utm_campaign=Rewards" - var skippable : Boolean = false - var duration : Int = 30 + var streak: StreakData = StreakData(0, 0, 0) + var activeAd: Int = 0 + var adLink: String = + "https://store.hypixel.net/?utm_source=rewards-video&utm_medium=website&utm_content=TRsCiBNYY7M&utm_campaign=Rewards" + var skippable: Boolean = false + var duration: Int = 30 init { - val json = GSON.fromJson(data.group("data"), JsonObject::class.java) - json.get("rewards")?.let { - if (it.isJsonArray) { - it.asJsonArray.forEach { jsonObject -> - val rewardObject = jsonObject.asJsonObject - rewards.add(RewardData( - RewardRarity.valueOf(rewardObject.get("rarity").asString!!), - rewardObject.get("reward").asString!!, - if (rewardObject.has("amount")) rewardObject.get("amount").asInt else null, - if (rewardObject.has("intlist")) rewardObject.get("intlist").asJsonArray.size() else null, - if (rewardObject.has("gameType")) GameMode.getModeFromId(rewardObject.get("gameType").asString) else null, - JsonUtils.getString(rewardObject, "package", null), - JsonUtils.getString(rewardObject, "key", null), - )) - } - } + GSON.fromJson(data.groups["data"]!!.value, JsonWebData::class.java)?.let { + rewards.addAll(it.rewards) + streak = it.dailyStreak + activeAd = it.activeAd + adLink = it.ad.link + duration = it.ad.duration + skippable = it.skippable } - - json.get("dailyStreak")?.let { - val streakObject = it.asJsonObject - streak = StreakData(JsonUtils.getInt(streakObject, "value", 0), - JsonUtils.getInt(streakObject, "score", 0), - JsonUtils.getInt(streakObject, "highScore", 0) - ) - } - - json.get("activeAd")?.let { activeAd = it.asInt } - json.get("ad")?.let { jsonObject -> - val adObject = jsonObject.asJsonObject - adObject.get("link")?.let { adLink = it.asString } - adObject.get("duration")?.let { duration = it.asInt } - } - json.get("skippable")?.let { skippable = it.asBoolean } - } + private data class JsonWebData( + val rewards: List<RewardData>, + val dailyStreak: StreakData, + val activeAd: Int, + val ad: AdData, + val skippable: Boolean + ) + }
\ No newline at end of file diff --git a/src/main/kotlin/tech/thatgravyboat/rewardclaim/ui/RewardClaimGui.kt b/src/main/kotlin/tech/thatgravyboat/rewardclaim/ui/RewardClaimGui.kt index 8f1d535..0e5b054 100644 --- a/src/main/kotlin/tech/thatgravyboat/rewardclaim/ui/RewardClaimGui.kt +++ b/src/main/kotlin/tech/thatgravyboat/rewardclaim/ui/RewardClaimGui.kt @@ -16,16 +16,14 @@ import java.awt.Color import java.net.* import java.nio.charset.Charset import java.util.concurrent.TimeUnit -import java.util.regex.Matcher -import java.util.regex.Pattern private val BUTTON_HOVER = Color(0, 212, 105) -private val SECURITY_REGEX = Pattern.compile("window\\.securityToken = \"(?<token>.*)\";") -private val DATA_REGEX = Pattern.compile("window\\.appData = '(?<data>\\{.*})';") -private val I18N_REGEX = Pattern.compile("window.i18n = \\{(?<translations>.*)};", Pattern.DOTALL) +private val SECURITY_REGEX = Regex("window\\.securityToken = \"(?<token>.*)\";") +private val DATA_REGEX = Regex("window\\.appData = '(?<data>\\{.*})';") +private val I18N_REGEX = Regex("window.i18n = \\{(?<translations>.*)};", RegexOption.DOT_MATCHES_ALL) -class RewardClaimGui(private val id : String) : WindowScreen() { +class RewardClaimGui(private val id: String) : WindowScreen() { private var state: State = State.LOADING private var selected = -1 @@ -48,32 +46,29 @@ class RewardClaimGui(private val id : String) : WindowScreen() { doOutput = true inputStream.use { val html = IOUtils.toString(it, Charset.defaultCharset()) - val securityMatcher: Matcher = SECURITY_REGEX.matcher(html) - val dataMatcher: Matcher = DATA_REGEX.matcher(html) - val i18nMatcher: Matcher = I18N_REGEX.matcher(html) - val securityFound = securityMatcher.find() - val dataFound = dataMatcher.find() - val i18nFound = i18nMatcher.find() - - if (securityFound && dataFound && i18nFound) { + val securityMatcher = SECURITY_REGEX.find(html) + val dataMatcher = DATA_REGEX.find(html) + val i18nMatcher = I18N_REGEX.find(html) + + if (securityMatcher != null && dataMatcher != null && i18nMatcher != null) { data = WebData(securityMatcher, dataMatcher, i18nMatcher) if (data.rewards.isEmpty()) { state = State.FAILED_REWARDS errorPopup("Rewards were empty.") - }else { + } else { state = State.SUCCESSFUL updateElements() } - if (data.skippable || data.duration == 0){ + if (data.skippable || data.duration == 0) { adPopup(true) - }else { + } else { schedule({ adPopup(true) }, data.duration.toLong(), TimeUnit.SECONDS) } } else { state = State.FAILED_REWARDS - errorPopup("Regex could not be found.\nSecurity: $securityFound\nI18n: $i18nFound\nData: $dataFound") + errorPopup("Regex could not be found.\nSecurity: ${securityMatcher != null}\nI18n: ${i18nMatcher != null}\nData: $${dataMatcher != null}") } } } @@ -171,7 +166,7 @@ class RewardClaimGui(private val id : String) : WindowScreen() { } childOf background } - private val streaks = Array(9){ i -> + private val streaks = Array(9) { i -> UICircle(5f, VigilancePalette.getDivider(), 15).let { it.constrain { x = ((15.percent() + (15.percent() - 0.5.pixel())) - 45.pixel()) + (it.getWidth() * i).pixel() @@ -182,21 +177,22 @@ class RewardClaimGui(private val id : String) : WindowScreen() { //endregion - private val rewards = Array(3){ i -> UIReward(57.5.percent(), 30.percent() + (18 * i).percent()) childOf background}.also { - for (reward in it) { - reward.onMouseClick { event -> - if (event.mouseButton == 0 && state == State.SUCCESSFUL) { - for (j in 0..2) { - it[j].setSelected(it[j] == reward) - if (it[j] != event.currentTarget) continue - selected = j - selectedReward.updateInfo(data.rewards[selected], data.language) + private val rewards = + Array(3) { i -> UIReward(57.5.percent(), 30.percent() + (18 * i).percent()) childOf background }.also { + for (reward in it) { + reward.onMouseClick { event -> + if (event.mouseButton == 0 && state == State.SUCCESSFUL) { + for (j in 0..2) { + it[j].setSelected(it[j] == reward) + if (it[j] != event.currentTarget) continue + selected = j + selectedReward.updateInfo(data.rewards[selected], data.language) + } } } + reward.hide(true) } - reward.hide(true) } - } private fun updateElements() { data.let { @@ -213,56 +209,62 @@ class RewardClaimGui(private val id : String) : WindowScreen() { } } - private var popup : UIPopup? = null + private var popup: UIPopup? = null - private fun errorPopup(error : String) { + private fun errorPopup(error: String) { Window.enqueueRenderOperation { popup?.let { - if (it.parent.hasParent){ + if (it.parent.hasParent) { it.parent.removeChild(it) popup = null } } popup = UIPopup( - "${ChatColor.RED}An Error Occurred!", error, - UIImage.ofResourceCached("/vigilance/cancel.png"), - { restorePreviousScreen() }, - "${ChatColor.BOLD}Close", - UIImage.ofResourceCached("/rewardclaim/external_link.png"), - { UDesktop.browse(URI("https://rewards.hypixel.net/claim-reward/${id}")) }, - "${ChatColor.BOLD}Reward" + "${ChatColor.RED}An Error Occurred!", error, + UIImage.ofResourceCached("/vigilance/cancel.png"), + { restorePreviousScreen() }, + "${ChatColor.BOLD}Close", + UIImage.ofResourceCached("/rewardclaim/external_link.png"), + { UDesktop.browse(URI("https://rewards.hypixel.net/claim-reward/${id}")) }, + "${ChatColor.BOLD}Reward" ) childOf this.window } } private fun confirmPopup() { - popup = UIPopup("Confirmation", "Are you sure you want to claim this reward. Click 'Back' if you would like to change which reward you would like to claim or 'Continue' if you like to go ahead with your reward.", - null, { removePopup() }, "${ChatColor.BOLD}Back", - null, { - runAsync { - try { - (URL("https://rewards.hypixel.net/claim-reward/claim?option=$selected&id=$id&activeAd=${data.activeAd}&_csrf=${data.securityToken}&watchedFallback=false").openConnection() as HttpURLConnection).apply { - requestMethod = "POST" - useCaches = true - addRequestProperty("User-Agent", RewardConfiguration.userAgent) - readTimeout = 15000 - connectTimeout = 15000 - responseCode - CookieManager.setDefault(null) - restorePreviousScreen() - } - }catch (ignored : Exception){ - //IGNORED + popup = UIPopup( + "Confirmation", + "Are you sure you want to claim this reward. Click 'Back' if you would like to change which reward you would like to claim or 'Continue' if you like to go ahead with your reward.", + null, + { removePopup() }, + "${ChatColor.BOLD}Back", + null, + { + runAsync { + try { + (URL("https://rewards.hypixel.net/claim-reward/claim?option=$selected&id=$id&activeAd=${data.activeAd}&_csrf=${data.securityToken}&watchedFallback=false").openConnection() as HttpURLConnection).apply { + requestMethod = "POST" + useCaches = true + addRequestProperty("User-Agent", RewardConfiguration.userAgent) + readTimeout = 15000 + connectTimeout = 15000 + responseCode + CookieManager.setDefault(null) + restorePreviousScreen() } + } catch (ignored: Exception) { + //IGNORED } - }, "${ChatColor.BOLD}Continue" + } + }, + "${ChatColor.BOLD}Continue" ) childOf this.window } private fun removePopup() { Window.enqueueRenderOperation { popup?.let { - if (it.parent.hasParent){ + if (it.parent.hasParent) { it.parent.removeChild(it) popup = null } @@ -273,7 +275,7 @@ class RewardClaimGui(private val id : String) : WindowScreen() { private fun adPopup(skip: Boolean) { Window.enqueueRenderOperation { popup?.let { - if (it.parent.hasParent){ + if (it.parent.hasParent) { it.parent.removeChild(it) popup = null } @@ -282,14 +284,20 @@ class RewardClaimGui(private val id : String) : WindowScreen() { UIPopup( "Reward Claim AD", "Hypixel is a great server and as such we don't want to remove their ad for their store. You can click the skip button when it appears to remove this message and claim your reward.", - UIImage.ofResourceCached("/rewardclaim/external_link.png"), { UDesktop.browse(URI(data.adLink)) }, "${ChatColor.BOLD}Store", - null, { removePopup() }, "${ChatColor.BOLD}Skip" + UIImage.ofResourceCached("/rewardclaim/external_link.png"), + { UDesktop.browse(URI(data.adLink)) }, + "${ChatColor.BOLD}Store", + null, + { removePopup() }, + "${ChatColor.BOLD}Skip" ) childOf this.window } else { UIPopup( "Reward Claim AD", "Hypixel is a great server and as such we don't want to remove their ad for their store. You can click the skip button when it appears to remove this message and claim your reward.", - UIImage.ofResourceCached("/rewardclaim/external_link.png"), { UDesktop.browse(URI(data.adLink)) }, "${ChatColor.BOLD}Store" + UIImage.ofResourceCached("/rewardclaim/external_link.png"), + { UDesktop.browse(URI(data.adLink)) }, + "${ChatColor.BOLD}Store" ) childOf this.window } } diff --git a/src/main/kotlin/tech/thatgravyboat/rewardclaim/ui/UIButton.kt b/src/main/kotlin/tech/thatgravyboat/rewardclaim/ui/UIButton.kt index e1037d0..ec92f25 100644 --- a/src/main/kotlin/tech/thatgravyboat/rewardclaim/ui/UIButton.kt +++ b/src/main/kotlin/tech/thatgravyboat/rewardclaim/ui/UIButton.kt @@ -11,7 +11,13 @@ import java.awt.Color private val BUTTON_HOVER = Color(0, 212, 105) -class UIButton(private val image : UIImage?, private val widthIn : Float, private var xConstraint : XConstraint, private val text : UIText, alignment: Alignment) : UIBlock(VigilancePalette.getAccent()) { +class UIButton( + private val image: UIImage?, + private val widthIn: Float, + private var xConstraint: XConstraint, + private val text: UIText, + alignment: Alignment +) : UIBlock(VigilancePalette.getAccent()) { init { if (alignment == Alignment.LEFT) { diff --git a/src/main/kotlin/tech/thatgravyboat/rewardclaim/ui/UIPopup.kt b/src/main/kotlin/tech/thatgravyboat/rewardclaim/ui/UIPopup.kt index a3b4363..62734c4 100644 --- a/src/main/kotlin/tech/thatgravyboat/rewardclaim/ui/UIPopup.kt +++ b/src/main/kotlin/tech/thatgravyboat/rewardclaim/ui/UIPopup.kt @@ -12,11 +12,16 @@ import gg.essential.elementa.utils.withAlpha import gg.essential.vigilance.gui.VigilancePalette import gg.essential.vigilance.gui.VigilancePalette.getBackground -class UIPopup private constructor(title : String, text : String) : UIBlock(getBackground().withAlpha(200)) { +class UIPopup private constructor(title: String, text: String) : UIBlock(getBackground().withAlpha(200)) { private val box: UIBlock - constructor(title : String, text : String, image : UIImage? = null, event : (UIComponent.(event: UIClickEvent) -> Unit), buttonText : String + constructor( + title: String, + text: String, + image: UIImage? = null, + event: (UIComponent.(event: UIClickEvent) -> Unit), + buttonText: String ) : this(title, text) { val btnText = UIText(buttonText, false) @@ -25,9 +30,10 @@ class UIPopup private constructor(title : String, text : String) : UIBlock(getBa UIButton(image, width, CenterConstraint(), btnText, Alignment.MIDDLE).onMouseClick(event) childOf box } - constructor(title : String, text : String, - image1 : UIImage? = null, event1 : (UIComponent.(event: UIClickEvent) -> Unit), buttonText : String, - image2 : UIImage? = null, event2 : (UIComponent.(event: UIClickEvent) -> Unit), buttonText2 : String + constructor( + title: String, text: String, + image1: UIImage? = null, event1: (UIComponent.(event: UIClickEvent) -> Unit), buttonText: String, + image2: UIImage? = null, event2: (UIComponent.(event: UIClickEvent) -> Unit), buttonText2: String ) : this(title, text) { val btn1Text = UIText(buttonText, false) @@ -37,8 +43,20 @@ class UIPopup private constructor(title : String, text : String) : UIBlock(getBa val width = btn1Width.coerceAtLeast(btn2Width) - UIButton(image1, width, CenterConstraint() - 5.percent(), btn1Text, Alignment.RIGHT).onMouseClick(event1) childOf box - UIButton(image2, width, CenterConstraint() + 5.percent(), btn2Text, Alignment.LEFT).onMouseClick(event2) childOf box + UIButton( + image1, + width, + CenterConstraint() - 5.percent(), + btn1Text, + Alignment.RIGHT + ).onMouseClick(event1) childOf box + UIButton( + image2, + width, + CenterConstraint() + 5.percent(), + btn2Text, + Alignment.LEFT + ).onMouseClick(event2) childOf box } init { diff --git a/src/main/kotlin/tech/thatgravyboat/rewardclaim/ui/UIReward.kt b/src/main/kotlin/tech/thatgravyboat/rewardclaim/ui/UIReward.kt index da5014f..02408d4 100644 --- a/src/main/kotlin/tech/thatgravyboat/rewardclaim/ui/UIReward.kt +++ b/src/main/kotlin/tech/thatgravyboat/rewardclaim/ui/UIReward.kt @@ -3,6 +3,7 @@ package tech.thatgravyboat.rewardclaim.ui import gg.essential.elementa.components.UIBlock import gg.essential.elementa.components.UIImage import gg.essential.elementa.components.UIText +import gg.essential.elementa.constraints.CenterConstraint import gg.essential.elementa.constraints.XConstraint import gg.essential.elementa.constraints.YConstraint import gg.essential.elementa.dsl.* @@ -11,15 +12,17 @@ import gg.essential.elementa.utils.withAlpha import gg.essential.universal.ChatColor import gg.essential.vigilance.gui.VigilancePalette import tech.thatgravyboat.rewardclaim.MappedImageCache +import tech.thatgravyboat.rewardclaim.RewardConfiguration import tech.thatgravyboat.rewardclaim.RewardLanguage import tech.thatgravyboat.rewardclaim.types.RewardData -class UIReward(xConstraint: XConstraint, yConstraint: YConstraint) : UIBlock(VigilancePalette.getHighlight().withAlpha(204)) { +class UIReward(xConstraint: XConstraint, yConstraint: YConstraint) : + UIBlock(VigilancePalette.getHighlight().withAlpha(204)) { - private val imageBackground : UIBlock - private val title : UIText - private val rarityDesc : UIText - private val amountDesc : UIText + private val imageBackground: UIBlock + private val title: UIText + private val rarityDesc: UIText + private val amountDesc: UIText init { constrain { @@ -64,20 +67,20 @@ class UIReward(xConstraint: XConstraint, yConstraint: YConstraint) : UIBlock(Vig amountDesc = UIText("Amount: ${ChatColor.GOLD}0").constrain { x = rightSideStart - y = 26.percent() + (5+rarityDesc.getHeight()).pixel() + y = 26.percent() + (5 + rarityDesc.getHeight()).pixel() } childOf this amountDesc.hide(true) } - fun setSelected(selected : Boolean) { + fun setSelected(selected: Boolean) { if (selected) { enableEffect(OutlineEffect(VigilancePalette.getAccent(), 1F)) - }else { + } else { removeEffect<OutlineEffect>() } } - fun setData(data : RewardData, language : RewardLanguage) { + fun setData(data: RewardData, language: RewardLanguage) { title.setText(data.getDisplayName(language)) rarityDesc.setText("Rarity: ${data.rarity.color}${language.translate(data.rarity.translationKey)}") @@ -86,16 +89,21 @@ class UIReward(xConstraint: XConstraint, yConstraint: YConstraint) : UIBlock(Vig amountDesc.unhide(true) } - data.boxes?.let { - amountDesc.setText("Boxes: ${ChatColor.GOLD}$it") + data.intlist?.let { + amountDesc.setText("Boxes: ${ChatColor.GOLD}${it.size}") amountDesc.unhide(true) } data.image?.let { it.url?.let { url -> + val imageType = RewardConfiguration.getImageType(it.imageType) UIImage.ofURL(url, MappedImageCache).constrain { - width = 100.percent() - height = it.height.percent() + width = imageType.width.percent() + height = imageType.height.percent() + if (imageType.center) { + x = CenterConstraint() + y = CenterConstraint() + } } childOf imageBackground } } diff --git a/src/main/kotlin/tech/thatgravyboat/rewardclaim/ui/UISelectedReward.kt b/src/main/kotlin/tech/thatgravyboat/rewardclaim/ui/UISelectedReward.kt index 47763dc..863ebc5 100644 --- a/src/main/kotlin/tech/thatgravyboat/rewardclaim/ui/UISelectedReward.kt +++ b/src/main/kotlin/tech/thatgravyboat/rewardclaim/ui/UISelectedReward.kt @@ -4,6 +4,7 @@ import gg.essential.elementa.components.UIBlock import gg.essential.elementa.components.UIImage import gg.essential.elementa.components.UIText import gg.essential.elementa.components.UIWrappedText +import gg.essential.elementa.constraints.CenterConstraint import gg.essential.elementa.constraints.XConstraint import gg.essential.elementa.dsl.* import gg.essential.elementa.effects.OutlineEffect @@ -11,12 +12,13 @@ import gg.essential.elementa.utils.withAlpha import gg.essential.universal.ChatColor import gg.essential.vigilance.gui.VigilancePalette import tech.thatgravyboat.rewardclaim.MappedImageCache +import tech.thatgravyboat.rewardclaim.RewardConfiguration import tech.thatgravyboat.rewardclaim.RewardLanguage import tech.thatgravyboat.rewardclaim.types.RewardData -class UISelectedReward(middle : XConstraint) : UIBlock(VigilancePalette.getHighlight().withAlpha(204)) { +class UISelectedReward(middle: XConstraint) : UIBlock(VigilancePalette.getHighlight().withAlpha(204)) { - private var image : UIImage? = null + private var image: UIImage? = null private val displayName = UIText("Select a Reward!").constrain { x = 31.percent() @@ -68,16 +70,21 @@ class UISelectedReward(middle : XConstraint) : UIBlock(VigilancePalette.getHighl rarity.setText("Rarity: ${data.rarity.color}${language.translate(data.rarity.translationKey)}") if (data.amount != null) amount.setText("Amount: ${ChatColor.GOLD}${data.amount}") - else if (data.boxes != null) amount.setText("Boxes: ${ChatColor.GOLD}${data.boxes}") + else if (data.intlist != null) amount.setText("Boxes: ${ChatColor.GOLD}${data.intlist.size}") else amount.setText("") desc.setText(data.getDescription(language)) data.image?.let { it.url?.let { url -> + val imageType = RewardConfiguration.getImageType(it.imageType) image?.let(imageBackground::removeChild) image = UIImage.ofURL(url, MappedImageCache).constrain { - height = it.height.percent() - width = 100.percent() + width = imageType.width.percent() + height = imageType.height.percent() + if (imageType.center) { + x = CenterConstraint() + y = CenterConstraint() + } } childOf imageBackground } } |