Skip to content

Commit a1898c9

Browse files
committed
add GithubAPI
1 parent a3533a6 commit a1898c9

5 files changed

Lines changed: 139 additions & 20 deletions

File tree

Core/src/main/kotlin/io/github/grassproject/framework/core/GPFrameworkEngine.kt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
package io.github.grassproject.framework.core
22

3-
import io.github.grassproject.framework.events.GPPluginUnregisterEvent
43
import io.github.grassproject.framework.events.GPPluginRegisterEvent
4+
import io.github.grassproject.framework.events.GPPluginUnregisterEvent
55
import io.github.grassproject.framework.exepction.FailToCallEvent
66
import io.github.grassproject.framework.util.GPLogger
77

Core/src/main/kotlin/io/github/grassproject/framework/core/GPPlugin.kt

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ abstract class GPPlugin : JavaPlugin(), GPFramework {
99
val authors = pluginMeta.authors
1010
val description = pluginMeta.description
1111
val apiVersion = pluginMeta.apiVersion
12-
val logger = GPLogger
12+
lateinit var logger: GPLogger
1313

1414
override fun onLoad() {
1515
load()
@@ -24,6 +24,7 @@ abstract class GPPlugin : JavaPlugin(), GPFramework {
2424

2525
enable()
2626
GPFrameworkEngine.register(this)
27+
logger=GPLogger(this)
2728
}
2829

2930
override fun onDisable() {
Lines changed: 99 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,102 @@
11
package io.github.grassproject.framework.github
22

3-
@ExperimentalStdlibApi
4-
internal object GithubAPI {
3+
import com.google.gson.Gson
4+
import com.google.gson.JsonObject
5+
import io.github.grassproject.framework.core.GPPlugin
6+
import io.github.grassproject.framework.util.GPLogger
7+
import java.io.File
8+
import java.net.HttpURLConnection
9+
import java.net.URL
10+
import java.nio.file.Files
11+
import java.nio.file.StandardCopyOption
12+
13+
@Deprecated("TEST")
14+
object GithubAPI {
15+
private const val ORG="GrassProject"
16+
private const val REPO="GPFramework"
17+
private const val GITHUB_API="https://api.github.com/repos/${ORG}/${REPO}/releases/latest"
18+
19+
fun isLatest(instance: GPPlugin): Boolean {
20+
val latest = getLatest() ?: return true
21+
val latestRaw = latest.get("ver").asString
22+
val currentRaw = instance.version
23+
24+
fun parseVersion(ver: String): Pair<List<Int>, String?> {
25+
val parts = ver.split("-", limit = 2)
26+
val numbers = parts[0].split(".").mapNotNull { it.toIntOrNull() }
27+
val tag = if (parts.size > 1) parts[1].lowercase() else null
28+
return numbers to tag
29+
}
30+
31+
val (latestNums, latestTag) = parseVersion(latestRaw)
32+
val (currentNums, currentTag) = parseVersion(currentRaw)
33+
34+
val maxLen = maxOf(latestNums.size, currentNums.size)
35+
for (i in 0 until maxLen) {
36+
val cur = currentNums.getOrNull(i) ?: 0
37+
val lat = latestNums.getOrNull(i) ?: 0
38+
if (cur < lat) return false
39+
if (cur > lat) return true
40+
}
41+
42+
return when {
43+
currentTag == null && latestTag != null -> true
44+
currentTag != null && latestTag == null -> false
45+
currentTag == null && latestTag == null -> true
46+
else -> {
47+
val order = listOf("ALPHA", "BETA", "RC", "SNAPSHOT")
48+
val curIndex = order.indexOfFirst { currentTag!!.contains(it) }
49+
.takeIf { it >= 0 } ?: Int.MAX_VALUE
50+
val latIndex = order.indexOfFirst { latestTag!!.contains(it) }
51+
.takeIf { it >= 0 } ?: Int.MAX_VALUE
52+
curIndex >= latIndex
53+
}
54+
}
55+
}
56+
57+
fun downloadAndReplace(plugin: GPPlugin): Boolean {
58+
val latest = getLatest() ?: return false
59+
val downloadUrl = latest.get("download")?.asString ?: return false
60+
61+
62+
return try {
63+
val pluginsDir = File("plugins")
64+
val newFile = File(pluginsDir, "${plugin.name}.jar.new")
65+
URL(downloadUrl).openStream().use { input ->
66+
Files.copy(input, newFile.toPath(), StandardCopyOption.REPLACE_EXISTING)
67+
}
68+
GPLogger.info("새 버전을 다운로드했습니다. 서버 재시작 후 적용됩니다.")
69+
true
70+
} catch (e: Exception) {
71+
GPLogger.warning("Fail to download UPDATE: ${e.message}")
72+
false
73+
}
74+
}
75+
76+
fun getLatest(): JsonObject {
77+
val json= JsonObject()
78+
val data=Gson().fromJson(fetchData(GITHUB_API), JsonObject::class.java)
79+
80+
json.addProperty("ver", data.get("tag_name").asString)
81+
json.addProperty("published", data.get("published_at").asString)
82+
83+
val assets = data.getAsJsonArray("assets")
84+
val downloadUrl = assets[0].asJsonObject.get("browser_download_url").asString
85+
json.addProperty("download", downloadUrl)
86+
87+
return json
88+
}
89+
90+
private fun fetchData(url: String): String {
91+
return URL(url).httpRequest {
92+
requestMethod = "GET"
93+
setRequestProperty("Accept", "application/vnd.github.v3+json")
94+
// setRequestProperty("Authorization", "")
95+
inputStream.bufferedReader().use { it.readText() }
96+
}
97+
}
98+
99+
private fun <T> URL.httpRequest(requester: (HttpURLConnection.() -> T)): T {
100+
return with(openConnection() as HttpURLConnection) { requester.invoke(this) }
101+
}
5102
}
Lines changed: 30 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,42 @@
11
package io.github.grassproject.framework.util
22

3+
import io.github.grassproject.framework.core.GPPlugin
34
import io.github.grassproject.framework.util.component.toMiniMessage
5+
import net.kyori.adventure.text.Component
46
import org.bukkit.Bukkit
57

6-
object GPLogger {
7-
private val prefix="<#96f19c>GPFramework</#96f19c><#989c99> > </#989c99>"
8+
class GPLogger(private val plugin: GPPlugin? = null) {
9+
private val prefix = "<#96f19c>{gp-prefix}</#96f19c><#989c99> > </#989c99>"
810

9-
@JvmStatic
10-
fun info(string: String) {
11-
Bukkit.getConsoleSender().sendMessage { "${prefix}<white>${string}</white>".toMiniMessage() }
11+
private fun format(color: String, message: String): Component {
12+
val name = plugin?.name ?: "GPFramework"
13+
return "${prefix.replace("{gp-prefix}", name)}<$color>$message</$color>".toMiniMessage()
1214
}
1315

14-
@JvmStatic
15-
fun warning(string: String) {
16-
Bukkit.getConsoleSender().sendMessage { "${prefix}<yellow>${string}</yellow>".toMiniMessage() }
17-
}
16+
fun info(string: String) = send("white", string)
17+
fun warning(string: String) = send("yellow", string)
18+
fun suc(string: String) = send("green", string)
19+
fun bug(string: String) = send("red", string)
1820

19-
@JvmStatic
20-
fun suc(string: String) {
21-
Bukkit.getConsoleSender().sendMessage { "${prefix}<green>${string}</green>".toMiniMessage() }
21+
private fun send(color: String, string: String) {
22+
Bukkit.getConsoleSender().sendMessage(format(color, string))
2223
}
2324

24-
@JvmStatic
25-
fun bug(string: String) {
26-
Bukkit.getConsoleSender().sendMessage { "${prefix}<red>${string}</red>".toMiniMessage() }
25+
companion object {
26+
@JvmStatic
27+
@JvmName("log")
28+
fun info(string: String) = GPLogger().info(string)
29+
30+
@JvmStatic
31+
@JvmName("logSuc")
32+
fun suc(string: String) = GPLogger().suc(string)
33+
34+
@JvmStatic
35+
@JvmName("warn")
36+
fun warning(string: String) = GPLogger().warning(string)
37+
38+
@JvmStatic
39+
@JvmName("severe")
40+
fun bug(string: String) = GPLogger().bug(string)
2741
}
28-
}
42+
}

src/main/kotlin/io/github/grassproject/framework/GPFrameworkPlugin.kt

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import io.github.grassproject.framework.config.GPFile
55
import io.github.grassproject.framework.config.init
66
import io.github.grassproject.framework.core.GPPlugin
77
import io.github.grassproject.framework.database.DatabaseManager
8+
import io.github.grassproject.framework.github.GithubAPI
89

910
class GPFrameworkPlugin : GPPlugin() {
1011
companion object {
@@ -19,6 +20,12 @@ class GPFrameworkPlugin : GPPlugin() {
1920
}
2021

2122
override fun enable() {
23+
if (GithubAPI.isLatest(this)) {
24+
val data=GithubAPI.getLatest()
25+
logger.bug("New Version Released! ${data["published"]}")
26+
logger.bug("New: ${data["ver"]}, Now: $version")
27+
}
28+
2229
val config = GPFile(dataFolder, "config.yml")
2330
init(config)
2431
DatabaseManager.initConfig(config)

0 commit comments

Comments
 (0)