Skip to content

Commit

Permalink
Merge pull request #2 from WsureDev/mirai-archived
Browse files Browse the repository at this point in the history
commit
  • Loading branch information
WsureDev committed Dec 3, 2021
2 parents 27d3ad7 + 6e22432 commit 2354c92
Show file tree
Hide file tree
Showing 5 changed files with 75 additions and 24 deletions.
3 changes: 0 additions & 3 deletions src/main/kotlin/top/wsure/warframe/cache/CacheValue.kt
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
package top.wsure.warframe.cache

import kotlinx.serialization.Polymorphic
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json

/**
* FileName: CacheValue
Expand Down
13 changes: 5 additions & 8 deletions src/main/kotlin/top/wsure/warframe/cache/ExpirableCache.kt
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
package top.wsure.warframe.cache

import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import net.mamoe.mirai.console.data.SerializerAwareValue
import top.wsure.warframe.data.WorldStateData
import java.util.concurrent.ConcurrentMap
import top.wsure.warframe.utils.JsonUtils.jsonToObject
import top.wsure.warframe.utils.JsonUtils.objectToJson

/**
* FileName: ExpirableCache
Expand Down Expand Up @@ -33,9 +30,9 @@ class ExpirableCache<K>(
return delegate.keys
}

fun put(k: K, v: Any?, wait: Long?) {
fun put(k: K, v: Any, wait: Long?) {
val timeout = if (wait == null) 0 else (wait + System.currentTimeMillis())
delegate[k] = CacheValue(k, Json.encodeToString(v), timeout)
delegate[k] = CacheValue(k, v.objectToJson(), timeout)
}

override fun remove(key: K): CacheValue<K>? {
Expand All @@ -49,7 +46,7 @@ class ExpirableCache<K>(
}

inline fun <reified T> getData(key:K):T? {
return get(key)?.value?.let { Json{ ignoreUnknownKeys = true }.decodeFromString<T>(it) }
return get(key)?.value?.jsonToObject()
}

private fun recycle() {
Expand Down
5 changes: 2 additions & 3 deletions src/main/kotlin/top/wsure/warframe/task/WFTask.kt
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
package top.wsure.warframe.task

import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import net.mamoe.mirai.console.MiraiConsole
import net.mamoe.mirai.console.util.ConsoleExperimentalApi
import net.mamoe.mirai.message.data.content
Expand All @@ -13,6 +11,7 @@ import top.wsure.warframe.data.RemoteTask
import top.wsure.warframe.data.TaskEnum
import top.wsure.warframe.data.WorldStateData
import top.wsure.warframe.utils.CommandUtils
import top.wsure.warframe.utils.JsonUtils.objectToJson
import top.wsure.warframe.utils.NotifyUtils
import top.wsure.warframe.utils.OkHttpUtils

Expand Down Expand Up @@ -93,6 +92,6 @@ class WFTask(private val remoteTask: RemoteTask) {
private fun storeQueue(remoteTask: RemoteTask, queues: List<RemoteQueue>) {
val cacheKey = cacheQueueName(remoteTask)
ExpirableCache.CACHE_MAP[cacheKey] =
CacheValue(cacheKey, Json.encodeToString(queues), queues.maxOf { it.timeout })
CacheValue(cacheKey, queues.objectToJson(), queues.maxOf { it.timeout })
}
}
59 changes: 59 additions & 0 deletions src/main/kotlin/top/wsure/warframe/utils/JsonUtils.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package top.wsure.warframe.utils

import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.decodeFromJsonElement
import net.mamoe.mirai.utils.MiraiLogger
import org.slf4j.Logger
import org.slf4j.LoggerFactory

object JsonUtils {
val logger: MiraiLogger = MiraiLogger.Factory.create(this::class)
@OptIn(ExperimentalSerializationApi::class)
val formatter = Json {
ignoreUnknownKeys = true
encodeDefaults = true
explicitNulls = false
}

@OptIn(ExperimentalSerializationApi::class)
inline fun <reified T : Any> T.objectToJson(): String {
return formatter.encodeToString(this)
}

@OptIn(ExperimentalSerializationApi::class)
inline fun <reified T> String.jsonToObject(): T {
return formatter.decodeFromString(this)
}

@OptIn(ExperimentalSerializationApi::class)
inline fun <reified T> String.jsonToObjectOrNull(failureReason:Boolean = true): T? {
return kotlin.runCatching { formatter.decodeFromString<T>(this) }
.onFailure {
if(failureReason) {
logger.warning("format string to json failed !! string :$this", it)
}
}.getOrNull()
}

fun String.toJsonElement(): JsonElement {
return formatter.parseToJsonElement(this)
}

inline fun <reified T> JsonElement.jsonToObject(): T {
return formatter.decodeFromJsonElement(this)
}

@OptIn(ExperimentalSerializationApi::class)
inline fun <reified T> JsonElement.jsonToObjectOrNull(failureReason:Boolean = true): T? {
return kotlin.runCatching { formatter.decodeFromJsonElement<T>(this) }
.onFailure {
if(failureReason) {
logger.warning("format string to json failed !! string :$this", it)
}
}.getOrNull()
}
}
19 changes: 9 additions & 10 deletions src/main/kotlin/top/wsure/warframe/utils/OkHttpUtils.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,14 @@ package top.wsure.warframe.utils

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import net.mamoe.mirai.utils.MiraiLogger
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import top.wsure.warframe.utils.JsonUtils.jsonToObjectOrNull
import top.wsure.warframe.utils.JsonUtils.objectToJson
import java.io.InputStream
import java.util.concurrent.TimeUnit

Expand All @@ -22,7 +21,7 @@ import java.util.concurrent.TimeUnit
*/
class OkHttpUtils {
companion object {
private val logger: MiraiLogger = MiraiLogger.create(this::class.java.name)
private val logger: MiraiLogger = MiraiLogger.Factory.create(this::class)

private val client = OkHttpClient().newBuilder().readTimeout(60,TimeUnit.SECONDS).build()

Expand All @@ -46,9 +45,9 @@ class OkHttpUtils {
return response.body?.byteStream()!!
}

fun doPost(url: String,body:Any?):String?{
fun doPost(url: String,body:Any):String?{
val mediaType = "application/json; charset=utf-8".toMediaType()
val reqBody: RequestBody = Json.encodeToString(body).toRequestBody(mediaType)
val reqBody: RequestBody = body.objectToJson().toRequestBody(mediaType)
val request = Request.Builder()
.url(url)
.post(reqBody)
Expand All @@ -59,7 +58,7 @@ class OkHttpUtils {
}

suspend inline fun <reified T> doGetObject(url: String):T{
return asyncDoGet(url)?.let { Json{ ignoreUnknownKeys = true }.decodeFromString<T>(it) }!!
return asyncDoGet(url)?.jsonToObjectOrNull<T>()!!
}

suspend fun asyncDoGet(url: String):String?{
Expand All @@ -68,11 +67,11 @@ class OkHttpUtils {
}
}

suspend inline fun <reified T> doPostObject(url: String,body:Any?):T{
return asyncDoPost(url,body)?.let { Json{ ignoreUnknownKeys = true }.decodeFromString<T>(it) }!!
suspend inline fun <reified T> doPostObject(url: String,body:Any):T{
return asyncDoPost(url,body)?.jsonToObjectOrNull<T>()!!
}

suspend fun asyncDoPost(url: String,body:Any?):String?{
suspend fun asyncDoPost(url: String,body:Any):String?{
return withContext(Dispatchers.Default){
doPost(url,body)
}
Expand Down

0 comments on commit 2354c92

Please sign in to comment.