Implement plugin state (closes #603) (#622)

This commit is contained in:
Simon
2025-07-11 20:23:39 +02:00
committed by GitHub
parent a407471814
commit c4c39a8dd3
7 changed files with 92 additions and 28 deletions
+6
View File
@@ -1,5 +1,7 @@
import com.vanniktech.maven.publish.SonatypeHost
val jacksonVersion = "2.19.1"
plugins {
kotlin("jvm")
`java-library`
@@ -11,6 +13,10 @@ group = "org.gameyfin"
dependencies {
// PF4J (shared)
api("org.pf4j:pf4j:${rootProject.extra["pf4jVersion"]}")
// JSON serialization
compileOnly("com.fasterxml.jackson.core:jackson-databind:$jacksonVersion")
implementation("com.fasterxml.jackson.module:jackson-module-kotlin:$jacksonVersion")
}
mavenPublishing {
@@ -1,7 +1,14 @@
package org.gameyfin.pluginapi.core.wrapper
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.KotlinModule
import org.pf4j.Plugin
import org.pf4j.PluginWrapper
import java.nio.file.Files
import java.nio.file.Path
import kotlin.io.path.createFile
import kotlin.io.path.exists
import kotlin.io.path.fileSize
/**
* Abstract base class for all Gameyfin plugins.
@@ -25,20 +32,17 @@ abstract class GameyfinPlugin(wrapper: PluginWrapper) : Plugin(wrapper) {
* Supported logo file formats.
*/
val SUPPORTED_LOGO_FORMATS: List<String> = listOf("png", "jpg", "jpeg", "gif", "svg", "webp")
/**
* Reference to the current plugin instance.
*/
lateinit var plugin: GameyfinPlugin
private set
}
/**
* Initializes the plugin and sets the static plugin reference.
* State file for the plugin, used to persist plugin-specific state.
*/
init {
plugin = this
}
val stateFile: Path = Path.of("${wrapper.pluginId}.state.json")
/**
* JSON serializer for serializing and deserializing plugin state.
*/
val objectMapper: ObjectMapper = ObjectMapper().registerModule(KotlinModule.Builder().build())
/**
* Checks if the plugin contains a logo file in any supported format.
@@ -73,4 +77,18 @@ abstract class GameyfinPlugin(wrapper: PluginWrapper) : Plugin(wrapper) {
return null
}
inline fun <reified T> loadState(): T? {
if (!stateFile.exists() || stateFile.fileSize() == 0L) return null
return Files.newBufferedReader(stateFile).use {
objectMapper.readValue(it.readText(), T::class.java)
}
}
inline fun <reified T> saveState(state: T) {
if (!stateFile.exists()) stateFile.createFile()
Files.newBufferedWriter(stateFile).use {
it.write(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(state))
}
}
}