Skip to content

Commit

Permalink
refactor and clean up BaseConfigurationFactory.kt
Browse files Browse the repository at this point in the history
  • Loading branch information
SpoilerRules committed Mar 20, 2024
1 parent d7221d0 commit c439da8
Show file tree
Hide file tree
Showing 12 changed files with 101 additions and 110 deletions.
16 changes: 8 additions & 8 deletions src/main/kotlin/com/spoiligaming/generator/GeneratorBean.kt
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ object GeneratorBean {
val config = BaseConfigurationFactory.getInstance()

// reset isAnythingChanged to ensure concurrent operations work
BaseConfigurationFactory.isAnythingChanged = false
BaseConfigurationFactory.isConfigUpdated = false

if (isGenerationPaused.get()) return@timer

Expand All @@ -38,8 +38,8 @@ object GeneratorBean {
}

false -> {
val proxy = config.customProxy
val multithreading = config.multithreading.enabled
val proxy = config.proxySettings
val multithreading = config.multithreadingSettings.enabled
if ((proxy.proxyFilePath.isNotEmpty() && proxy.mode == 2 && proxy.enabled) || proxy.enabled && proxy.mode != 2 || !proxy.enabled) {
when {
proxy.mode in 1..3 && !multithreading -> NitroValidatorOrdinary.validateNitro(
Expand All @@ -59,14 +59,14 @@ object GeneratorBean {
}

private fun handleConcurrentValidation(initialNitroCode: String, config: BaseConfigurationFactory) {
val semaphore = Semaphore(config.multithreading.threadLimit)
val semaphore = Semaphore(config.multithreadingSettings.threadLimit)

runBlocking {
repeat(config.multithreading.threadLimit) {
repeat(config.multithreadingSettings.threadLimit) {
launch(Dispatchers.IO) {
var index = 0

while (isActive && !BaseConfigurationFactory.isAnythingChanged && !isGenerationPaused.get()) {
while (isActive && !BaseConfigurationFactory.isConfigUpdated && !isGenerationPaused.get()) {
semaphore.acquire()
val nitroCode =
if (index++ == 0) initialNitroCode else generateNitroCode(config.generalSettings.generatePromotionalGiftCode)
Expand All @@ -79,15 +79,15 @@ object GeneratorBean {
)
semaphore.release()
}
delay(config.multithreading.threadLaunchDelay)
delay(config.multithreadingSettings.threadLaunchDelay)
}
}
}
}
}

private fun validateNitro(nitroCode: String, config: BaseConfigurationFactory, threadIdentifier: String) {
when (config.customProxy.mode) {
when (config.proxySettings.mode) {
1 -> NitroValidatorSimpleMt.validateNitro(nitroCode, config, 0, threadIdentifier)
in 2..3 -> NitroValidatorAdvancedMt.validateNitro(nitroCode, config, 0, threadIdentifier)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,12 @@ object NitroValidationWrapper {
"User-Agent",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36"
)
if (config.customProxy.isAuthenticationRequired && config.customProxy.enabled && config.customProxy.mode == 1) {
if (config.proxySettings.isAuthenticationRequired && config.proxySettings.enabled && config.proxySettings.mode == 1) {
setRequestProperty(
"Proxy-Authorization",
"Basic ${
Base64.getEncoder()
.encodeToString("${config.customProxy.username}:${config.customProxy.password}".toByteArray())
.encodeToString("${config.proxySettings.username}:${config.proxySettings.password}".toByteArray())
}"
)
}
Expand Down Expand Up @@ -160,12 +160,12 @@ object NitroValidationWrapper {
crossinline validateFunction: (String, BaseConfigurationFactory, Int) -> Unit
) {
// no need for delay between retries when retry delay is <= 0 or custom proxy is enabled and custom proxy mode is in the range 2 to 3.
if (configuration.generalSettings.retryDelay > 0 && !(configuration.customProxy.enabled && configuration.customProxy.mode in 2..3)) {
if (configuration.generalSettings.retryDelay > 0 && !(configuration.proxySettings.enabled && configuration.proxySettings.mode in 2..3)) {
for (index in (configuration.generalSettings.retryDelay - 1) downTo 0) {
Logger.printWarning("${threadIdentity?.let { "${CEnum.RESET}[${CEnum.BLUE}THREAD: ${CEnum.RESET}${CEnum.CYAN}$it${CEnum.RESET}] " } ?: ""}Retrying validation of $nitroCode in ${CEnum.ORANGE}${index + 1}${CEnum.RESET} seconds.")
Thread.sleep(1000)
}
} else if (configuration.customProxy.mode in 2..3 && configuration.customProxy.enabled || configuration.generalSettings.retryDelay <= 0) {
} else if (configuration.proxySettings.mode in 2..3 && configuration.proxySettings.enabled || configuration.generalSettings.retryDelay <= 0) {
Logger.printWarning("${threadIdentity?.let { "${CEnum.RESET}[${CEnum.BLUE}THREAD: ${CEnum.RESET}${CEnum.CYAN}$it${CEnum.RESET}] " } ?: ""}Retrying validation of nitro code: $nitroCode.")
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,29 +72,29 @@ object NitroValidatorAdvancedMt {
config: BaseConfigurationFactory
): HttpURLConnection {
val proxy = when {
!config.customProxy.enabled -> Proxy.NO_PROXY
else -> when (config.customProxy.mode) {
!config.proxySettings.enabled -> Proxy.NO_PROXY
else -> when (config.proxySettings.mode) {
// keeping 1 case, we might merge advanced and simple mt validators.
1 -> Proxy(
config.customProxy.getProxyType(config.customProxy.protocol).also {
if (it == Proxy.Type.SOCKS && config.customProxy.isAuthenticationRequired) {
config.proxySettings.getProxyType(config.proxySettings.protocol).also {
if (it == Proxy.Type.SOCKS && config.proxySettings.isAuthenticationRequired) {
Authenticator.setDefault(object : Authenticator() {
override fun getPasswordAuthentication(): PasswordAuthentication {
return PasswordAuthentication(
config.customProxy.username,
config.customProxy.password.toCharArray()
config.proxySettings.username,
config.proxySettings.password.toCharArray()
)
}
})
}
},
InetSocketAddress(config.customProxy.host, config.customProxy.port.toInt())
InetSocketAddress(config.proxySettings.host, config.proxySettings.port.toInt())
)

else -> ProxyHandler.getNextProxy()?.let { proxyInfo ->
Logger.printDebug("[${CEnum.BLUE}THREAD: ${CEnum.RESET}${CEnum.CYAN}$threadIdentity${CEnum.RESET}] Using proxy: ${CEnum.CYAN}${proxyInfo.first}:${proxyInfo.second}${CEnum.RESET}")
Proxy(
config.customProxy.getProxyType(config.customProxy.protocol),
config.proxySettings.getProxyType(config.proxySettings.protocol),
InetSocketAddress(proxyInfo.first, proxyInfo.second)
)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,28 +82,28 @@ object NitroValidatorOrdinary {
*/
private fun getConnection(nitroCode: String, config: BaseConfigurationFactory): HttpURLConnection {
val proxy = when {
!config.customProxy.enabled -> Proxy.NO_PROXY
else -> when (config.customProxy.mode) {
!config.proxySettings.enabled -> Proxy.NO_PROXY
else -> when (config.proxySettings.mode) {
1 -> Proxy(
config.customProxy.getProxyType(config.customProxy.protocol).also {
if (it == Proxy.Type.SOCKS && config.customProxy.isAuthenticationRequired) {
config.proxySettings.getProxyType(config.proxySettings.protocol).also {
if (it == Proxy.Type.SOCKS && config.proxySettings.isAuthenticationRequired) {
Authenticator.setDefault(object : Authenticator() {
override fun getPasswordAuthentication(): PasswordAuthentication {
return PasswordAuthentication(
config.customProxy.username,
config.customProxy.password.toCharArray()
config.proxySettings.username,
config.proxySettings.password.toCharArray()
)
}
})
}
},
InetSocketAddress(config.customProxy.host, config.customProxy.port.toInt())
InetSocketAddress(config.proxySettings.host, config.proxySettings.port.toInt())
)

else -> ProxyHandler.getNextProxy()?.let { proxyInfo ->
Logger.printDebug("Using proxy: ${CEnum.CYAN}${proxyInfo.first}:${proxyInfo.second}${CEnum.RESET}")
Proxy(
config.customProxy.getProxyType(config.customProxy.protocol),
config.proxySettings.getProxyType(config.proxySettings.protocol),
InetSocketAddress(proxyInfo.first, proxyInfo.second)
)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,21 +24,21 @@ object NitroValidatorSimpleMt {
with(
URI("https://discordapp.com/api/v9/entitlements/gift-codes/$nitroCode?with_application=false&with_subscription_plan=true").toURL()
.openConnection(
if (config.customProxy.enabled && config.customProxy.mode == 1) {
if (config.proxySettings.enabled && config.proxySettings.mode == 1) {
Proxy(
config.customProxy.getProxyType(config.customProxy.protocol).also {
if (it == Proxy.Type.SOCKS && config.customProxy.isAuthenticationRequired) {
config.proxySettings.getProxyType(config.proxySettings.protocol).also {
if (it == Proxy.Type.SOCKS && config.proxySettings.isAuthenticationRequired) {
Authenticator.setDefault(object : Authenticator() {
override fun getPasswordAuthentication(): PasswordAuthentication {
return PasswordAuthentication(
config.customProxy.username,
config.customProxy.password.toCharArray()
config.proxySettings.username,
config.proxySettings.password.toCharArray()
)
}
})
}
},
InetSocketAddress(config.customProxy.host, config.customProxy.port.toInt())
InetSocketAddress(config.proxySettings.host, config.proxySettings.port.toInt())
)
} else {
Proxy.NO_PROXY
Expand Down
8 changes: 4 additions & 4 deletions src/main/kotlin/com/spoiligaming/generator/ProxyHandler.kt
Original file line number Diff line number Diff line change
Expand Up @@ -85,15 +85,15 @@ object ProxyHandler {
stackTrace.forEach { println(it) }
}*/

when (BaseConfigurationFactory.getInstance().customProxy.mode) {
when (BaseConfigurationFactory.getInstance().proxySettings.mode) {
1 -> {
"Proxy Mode was set to 'Static', and ProxyHandler class cannot be used for Static mode. Please contact your developer for assistance.".run {
Logger.printError(this)
throw UnsupportedOperationException(this)
}
}
2 -> loadProxiesFromFile(BaseConfigurationFactory.getInstance().customProxy.proxyFilePath)
3 -> loadProxiesFromURL(BaseConfigurationFactory.getInstance().customProxy.rawContentLinks.split(",").map { it.trim() }, BaseConfigurationFactory.getInstance().customProxy.rawContentSeparator)
2 -> loadProxiesFromFile(BaseConfigurationFactory.getInstance().proxySettings.proxyFilePath)
3 -> loadProxiesFromURL(BaseConfigurationFactory.getInstance().proxySettings.rawContentLinks.split(",").map { it.trim() }, BaseConfigurationFactory.getInstance().proxySettings.rawContentSeparator)
}
}

Expand All @@ -105,7 +105,7 @@ object ProxyHandler {
}

if (proxyIndex.get() >= proxies.size) {
if (BaseConfigurationFactory.getInstance().customProxy.recursiveUsaqe) {
if (BaseConfigurationFactory.getInstance().proxySettings.recursiveUsaqe) {
Logger.printWarning("All proxies are exhausted. Starting from the beginning of the proxy list.")
proxyIndex.set(0)
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ data class General(
@SerialName("alertWebhookForValidNitroCode") var alertWebhook: Boolean = true,
var discordWebhookURL: String = "https://dummylink.com/suspicious-webhook/",
@SerialName("retry") var retryTillValid: Boolean = true,
var retryDelay: Int = 3
var retryDelay: Int = 5
)

@Serializable
Expand Down Expand Up @@ -52,7 +52,7 @@ data class CustomProxy(
}

@Serializable
data class AutoClaimSettings(
data class AutoCl(
var enabled: Boolean = true,
var retryTillSuccess: Boolean = true,
var accountToken: String = "dGhpcyBpcyBhIGR1bW15IHRva2Vu"
Expand All @@ -71,53 +71,46 @@ data class Theme(
@Serializable
data class BaseConfigurationFactory(
@SerialName("General") var generalSettings: General = General(),
@SerialName("Custom Proxy") var customProxy: CustomProxy = CustomProxy(),
@SerialName("Multi Threading") var multithreading: Multithreading = Multithreading(),
@SerialName("Auto Claim") var autoClaimSettings: AutoClaimSettings = AutoClaimSettings(),
@SerialName("Custom Proxy") var proxySettings: CustomProxy = CustomProxy(),
@SerialName("Multi Threading") var multithreadingSettings: Multithreading = Multithreading(),
@SerialName("Auto Claim") var autoClaimSettings: AutoCl = AutoCl(),
@SerialName("Theme (unstable, do not modify)") var themeSettings: Theme = Theme()
) {
companion object {
var isAnythingChanged: Boolean = false
var isConfigUpdated: Boolean = false

private var pcFactoryInstance: BaseConfigurationFactory? = null
private var configFactoryInstance: BaseConfigurationFactory? = null
private val configFile = File("configuration.json")
private val jsonFormatter = Json {
encodeDefaults = true
prettyPrint = true
}

@Synchronized
fun getInstance(): BaseConfigurationFactory {
pcFactoryInstance = pcFactoryInstance ?: if (configFile.exists()) {
jsonFormatter.decodeFromString(serializer(), configFile.readText())
} else {
BaseConfigurationFactory().also {
configFile.writeText(jsonFormatter.encodeToString(serializer(), it))
}
}
return pcFactoryInstance!!
fun getInstance(): BaseConfigurationFactory = configFactoryInstance ?: BaseConfigurationFactory().also {
configFactoryInstance = it
ensureConfigExists(it, false)
}

fun createConfig() {
if (!configFile.exists()) {
private fun ensureConfigExists(config: BaseConfigurationFactory, updateOnly: Boolean) {
if (!configFile.exists() || updateOnly) {
runCatching {
configFile.writeText(jsonFormatter.encodeToString(serializer(), getInstance()))
}.onFailure {
Logger.printError("Failed to create configuration file: ${it.message}")
}.onSuccess {
Logger.printSuccess("Created configuration file.")
configFile.writeText(jsonFormatter.encodeToString(serializer(), config))
}.also { result ->
if (!updateOnly) {
result.onFailure {
Logger.printError("Failed to create configuration file: ${it.message}")
}.onSuccess {
Logger.printSuccess("Created configuration file.")
}
}
}
}
}

fun updateValue(updateFunction: BaseConfigurationFactory.() -> Unit) {
getInstance().apply(updateFunction)
isAnythingChanged = true
configFile.run {
if (exists()) {
writeText(jsonFormatter.encodeToString(serializer(), getInstance()))
} else createConfig()
}
isConfigUpdated = true
getInstance().apply(updateFunction).also { ensureConfigExists(it, true) }
}
}
}
6 changes: 2 additions & 4 deletions src/main/kotlin/com/spoiligaming/generator/gui/Initializer.kt
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package com.spoiligaming.generator.gui

import com.spoiligaming.generator.GeneratorBean
import com.spoiligaming.generator.configuration.BaseConfigurationFactory
import com.spoiligaming.logging.Logger
import javafx.application.Application
import javafx.beans.binding.Bindings
Expand All @@ -22,8 +21,8 @@ class Initializer : Application() {
private var yOffset = 0.0

override fun start(primaryStage: Stage) {
System.setProperty("prism.lcdtext", "false");
System.setProperty("prism.text", "t2k");
System.setProperty("prism.lcdtext", "false")
System.setProperty("prism.text", "t2k")
val borderPane = BorderPane()

borderPane.left = TabContainer()
Expand Down Expand Up @@ -66,7 +65,6 @@ class Initializer : Application() {
borderPane.bottom = addFundamentalButtons(primaryStage)

primaryStage.show()
BaseConfigurationFactory.createConfig()
GeneratorBean.startGeneratingNitro()
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ object ElementFilePicker {
): VBox {
val selectedFileLabel = Label().apply {
style = "-fx-text-fill: ${ColorPalette.TEXT_COLOR}; -fx-font-family: '${ResourceHandler.comfortaaBold.family}'; -fx-font-size: 13;"
text = if (BaseConfigurationFactory.getInstance().customProxy.proxyFilePath.isEmpty()) "No proxy file is selected." else "Selected proxy file: ${File(initialValue).name}"
text = if (BaseConfigurationFactory.getInstance().proxySettings.proxyFilePath.isEmpty()) "No proxy file is selected." else "Selected proxy file: ${File(initialValue).name}"
}

return VBox().apply {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ object ElementList {
setOnAction {
val selectedValue = this.value
BaseConfigurationFactory.updateValue {
customProxy.updateAction(selectedValue)
proxySettings.updateAction(selectedValue)
}
}
buttonCell = object : ListCell<String>() {
Expand Down
Loading

0 comments on commit c439da8

Please sign in to comment.