Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Multi resourcepack #259

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 14 additions & 4 deletions src/main/kotlin/one/oktw/galaxy/proxy/Main.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package one.oktw.galaxy.proxy

import com.google.inject.Inject
import com.velocitypowered.api.event.Subscribe
import com.velocitypowered.api.event.connection.DisconnectEvent
import com.velocitypowered.api.event.player.KickedFromServerEvent
import com.velocitypowered.api.event.player.ServerPostConnectEvent
import com.velocitypowered.api.event.player.ServerPreConnectEvent
Expand All @@ -23,7 +24,7 @@ import one.oktw.galaxy.proxy.event.TabListUpdater
import one.oktw.galaxy.proxy.kubernetes.KubernetesClient
import one.oktw.galaxy.proxy.pubsub.Manager
import one.oktw.galaxy.proxy.redis.RedisClient
import one.oktw.galaxy.proxy.resourcepack.ResourcePackHelper
import one.oktw.galaxy.proxy.resourcepack.ResourcePackManager
import org.slf4j.Logger
import java.net.InetSocketAddress
import kotlin.system.exitProcess
Expand Down Expand Up @@ -53,6 +54,8 @@ class Main : CoroutineScope by CoroutineScope(Dispatchers.Default + SupervisorJo
private set
lateinit var manager: Manager
private set
lateinit var resourcePackManager: ResourcePackManager
private set

@Inject
fun init(proxy: ProxyServer, logger: Logger) {
Expand All @@ -63,6 +66,7 @@ class Main : CoroutineScope by CoroutineScope(Dispatchers.Default + SupervisorJo
this.config = ConfigManager()
this.kubernetesClient = KubernetesClient()
this.redisClient = RedisClient()
this.resourcePackManager = ResourcePackManager()

manager = Manager(config.redisConfig.URI, config.redisConfig.PubSubPrefix)
manager.subscribe(MESSAGE_TOPIC)
Expand Down Expand Up @@ -113,14 +117,20 @@ class Main : CoroutineScope by CoroutineScope(Dispatchers.Default + SupervisorJo
it.result = ServerPreConnectEvent.ServerResult.allowed(lobby)
}

// Remove player on disconnect
proxy.eventManager.register(this, DisconnectEvent::class.java) {
this.resourcePackManager.removePlayer(it.player)
}

// Update resourcepacks
@Suppress("UnstableApiUsage") proxy.eventManager.register(this, ServerPostConnectEvent::class.java) {
// TODO: Get Galaxy Type
if (it.player.currentServer.get().serverInfo.name == "galaxy-lobby") {
ResourcePackHelper.trySendResourcePack(it.player, "lobby")
this.resourcePackManager.updatePlayerResourcePacks(it.player, "lobby")
} else {
// TODO: Check Galaxy Type
if (it.previousServer?.serverInfo?.name != "galaxy-lobby") return@register

ResourcePackHelper.trySendResourcePack(it.player, "normal_galaxy")
this.resourcePackManager.updatePlayerResourcePacks(it.player, "normal_galaxy")
}
}

Expand Down
26 changes: 19 additions & 7 deletions src/main/kotlin/one/oktw/galaxy/proxy/config/ConfigManager.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package one.oktw.galaxy.proxy.config

import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import kotlinx.coroutines.runBlocking
import one.oktw.galaxy.proxy.Main.Companion.main
import one.oktw.galaxy.proxy.config.model.GalaxySpec
Expand All @@ -22,10 +23,11 @@ class ConfigManager(private val basePath: Path = Paths.get("config")) {
lateinit var redisConfig: RedisConfig
private set
val galaxies = HashMap<String, GalaxySpec>()
val galaxiesResourcePack = ConcurrentHashMap<String, ResourcePack>()
val resourcePacks = ConcurrentHashMap<String, ResourcePack>()

init {
readConfig()
readResourcePacks()
readGalaxies(FileSystems.newFileSystem(this::class.java.getResource("/config")!!.toURI(), emptyMap<String, Any>()).getPath("/config/galaxies"))
readGalaxies(basePath.resolve("galaxies"))
}
Expand All @@ -41,6 +43,7 @@ class ConfigManager(private val basePath: Path = Paths.get("config")) {

fun reloadGalaxies() {
readGalaxies(basePath.resolve("galaxies"))
readResourcePacks()
}

private fun readConfig() {
Expand All @@ -56,13 +59,22 @@ class ConfigManager(private val basePath: Path = Paths.get("config")) {
Files.newBufferedReader(file).use { json ->
val galaxyName = file.fileName.toString().substringBeforeLast(".")
galaxies[galaxyName] = gson.fromJson(json, GalaxySpec::class.java)
runBlocking {
try {
galaxiesResourcePack[galaxyName] = galaxies[galaxyName]?.let { spec -> if (spec.ResourcePack.isNotBlank()) ResourcePack.new(spec.ResourcePack) else null } ?: return@runBlocking
} catch (e: Exception) {
main.logger.error("Resource pack load failed!", e)
}
}
}
}
}

private fun readResourcePacks() {
val mapType = object : TypeToken<Map<String, String>>() {}
val packs = fallbackToResource("resource_packs.json").reader().use { gson.fromJson(it, mapType) }
packs.forEach { pack ->
runBlocking {
try {
if (pack.value.isNotEmpty()) {
resourcePacks[pack.key] = ResourcePack.new(pack.value)
}
} catch (e: Exception) {
main.logger.error("Resource pack {} load failed!", pack.key, e)
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ data class GalaxySpec(
val Image: String,
val PullSecret: String,
val Type: GalaxyType,
val ResourcePack: String,
val ResourcePacks: Set<String>,
val Resource: GalaxyResource? = null,
val Storage: GalaxyStorage? = null
) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,10 @@
package one.oktw.galaxy.proxy.resourcepack

import com.google.common.hash.Hashing
import com.velocitypowered.api.proxy.player.ResourcePackInfo
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.withContext
import one.oktw.galaxy.proxy.Main.Companion.main
import java.io.FileNotFoundException
import java.io.IOException
import java.net.URI
Expand All @@ -32,13 +34,18 @@ class ResourcePack private constructor(url: String) {

var uri = URI(url)
private set
var hash:ByteArray
var hash: ByteArray
private set

init {
this.hash = getHashFromUri(uri)
}

fun packInfo(): ResourcePackInfo = main.proxy.createResourcePackBuilder(this.uri.toString())
.setHash(this.hash)
.setShouldForce(true)
.build()

@Throws(FileNotFoundException::class)
@Suppress("UnstableApiUsage", "DEPRECATION")
private fun getHashFromUri(uri: URI): ByteArray {
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package one.oktw.galaxy.proxy.resourcepack

import com.velocitypowered.api.proxy.Player
import com.velocitypowered.api.proxy.player.ResourcePackInfo
import one.oktw.galaxy.proxy.Main.Companion.main
import kotlin.math.min

class ResourcePackManager {
private val appliedPacks: MutableMap<Player, List<ResourcePackInfo>> = mutableMapOf()

fun updatePlayerResourcePacks(player: Player, galaxy: String) {
val new = main.config.galaxies[galaxy]?.ResourcePacks?.mapNotNull { main.config.resourcePacks[it]?.packInfo() } ?: emptyList()
val old = this.appliedPacks.getOrElse(player) { listOf() }

// Matching new resource packs
var updateIndex = old.lastIndex
for (i in 0..min(old.size, new.size)) {
if (old.getOrNull(i)?.hash != new.getOrNull(i)?.hash) {
updateIndex = i
break
}
}

// Remove not match resource packs
old.subList(updateIndex, old.size).forEach(player::removeResourcePacks)

// Add new resource packs
new.subList(updateIndex, new.size).forEach(player::sendResourcePacks)

// Save player resource packs state
appliedPacks[player] = new.toList()
}

// Remove player resource packs state
fun removePlayer(player: Player) {
appliedPacks.remove(player)
}
}
2 changes: 1 addition & 1 deletion src/main/resources/config/galaxies/lobby.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"Image": "registry.gitlab.com/oktw-network/galaxy",
"PullSecret": "",
"Type": "LOBBY",
"ResourcePack": "",
"ResourcePacks": ["base", "lobby"],
"Resource": {
"CPULimit": "4000m",
"CPURequest": "300m",
Expand Down
2 changes: 1 addition & 1 deletion src/main/resources/config/galaxies/normal_galaxy.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"Image": "registry.gitlab.com/oktw-network/galaxy",
"PullSecret": "",
"Type": "GALAXY",
"ResourcePack": "",
"ResourcePacks": ["base"],
"Resource": {
"CPULimit": "4000m",
"CPURequest": "300m",
Expand Down
4 changes: 4 additions & 0 deletions src/main/resources/config/resource_packs.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"base": "",
"lobby": ""
}