Skip to content
This repository has been archived by the owner on Nov 14, 2024. It is now read-only.

Commit

Permalink
Add JsonUtil
Browse files Browse the repository at this point in the history
  • Loading branch information
2dust authored and AnGgIt86 committed Sep 30, 2024
1 parent 3335ef4 commit 35b3f0d
Show file tree
Hide file tree
Showing 11 changed files with 83 additions and 61 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@ package com.neko.v2ray.service
import android.app.Service
import android.content.Intent
import android.os.IBinder
import com.google.gson.Gson
import com.neko.v2ray.AppConfig.MSG_MEASURE_CONFIG
import com.neko.v2ray.AppConfig.MSG_MEASURE_CONFIG_CANCEL
import com.neko.v2ray.AppConfig.MSG_MEASURE_CONFIG_SUCCESS
import com.neko.v2ray.dto.ConfigResult
import com.neko.v2ray.extension.serializable
import com.neko.v2ray.util.JsonUtil
import com.neko.v2ray.util.MessageUtil
import com.neko.v2ray.util.SpeedtestUtil
import com.neko.v2ray.util.Utils
Expand All @@ -33,8 +33,8 @@ class V2RayTestService : Service() {
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
when (intent?.getIntExtra("key", 0)) {
MSG_MEASURE_CONFIG -> {
val content = intent.serializable<String>("content")
val config = Gson().fromJson(content, ConfigResult::class.java)
val content = intent.serializable<String>("content") ?: ""
val config = JsonUtil.fromJson(content, ConfigResult::class.java)
realTestScope.launch {
val result = SpeedtestUtil.realPing(config.content)
MessageUtil.sendMsg2UI(this@V2RayTestService, MSG_MEASURE_CONFIG_SUCCESS, Pair(config.guid, result))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,13 @@ import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.material.appbar.MaterialToolbar
import com.google.android.material.appbar.CollapsingToolbarLayout
import com.google.gson.Gson
import com.neko.v2ray.AppConfig
import com.neko.v2ray.R
import com.neko.v2ray.databinding.ActivityRoutingSettingBinding
import com.neko.v2ray.dto.RulesetItem
import com.neko.v2ray.extension.toast
import com.neko.v2ray.helper.SimpleItemTouchHelperCallback
import com.neko.v2ray.util.JsonUtil
import com.neko.v2ray.util.MmkvManager
import com.neko.v2ray.util.MmkvManager.settingsStorage
import com.neko.v2ray.util.SettingsManager
Expand Down Expand Up @@ -145,7 +145,7 @@ class RoutingSettingActivity : BaseActivity() {
if (rulesetList.isNullOrEmpty()) {
toast(R.string.toast_failure)
} else {
Utils.setClipboard(this, Gson().toJson(rulesetList))
Utils.setClipboard(this, JsonUtil.toJson(rulesetList))
toast(R.string.toast_success)
}
true
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,14 @@ import com.google.android.material.appbar.MaterialToolbar
import com.blacksquircle.ui.editorkit.utils.EditorTheme
import com.blacksquircle.ui.language.json.JsonLanguage
import com.google.android.material.appbar.CollapsingToolbarLayout
import com.google.gson.Gson

import com.neko.v2ray.R
import com.neko.v2ray.databinding.ActivityServerCustomConfigBinding
import com.neko.v2ray.dto.EConfigType
import com.neko.v2ray.dto.ServerConfig
import com.neko.v2ray.dto.V2rayConfig
import com.neko.v2ray.extension.toast
import com.neko.v2ray.util.JsonUtil
import com.neko.v2ray.util.MmkvManager
import com.neko.v2ray.util.SoftInputAssist
import com.neko.v2ray.util.Utils
Expand Down Expand Up @@ -135,7 +136,7 @@ class ServerCustomConfigActivity : BaseActivity() {
}

val v2rayConfig = try {
Gson().fromJson(binding.editor.text.toString(), V2rayConfig::class.java)
JsonUtil.fromJson(binding.editor.text.toString(), V2rayConfig::class.java)
} catch (e: Exception) {
e.printStackTrace()
ToastCompat.makeText(this, "${getString(R.string.toast_malformed_josn)} ${e.cause?.message}", Toast.LENGTH_LONG).show()
Expand Down
23 changes: 5 additions & 18 deletions app/src/main/kotlin/com/neko/v2ray/util/AngConfigManager.kt
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import android.content.Context
import android.graphics.Bitmap
import android.text.TextUtils
import android.util.Log
import com.google.gson.Gson

import com.google.gson.GsonBuilder
import com.google.gson.JsonPrimitive
import com.google.gson.JsonSerializationContext
Expand Down Expand Up @@ -277,34 +277,21 @@ object AngConfigManager {
&& server.contains("routing")
) {
try {
//val gson = GsonBuilder().setPrettyPrinting().create()
val gson = GsonBuilder()
.setPrettyPrinting()
.disableHtmlEscaping()
.registerTypeAdapter( // custom serialiser is needed here since JSON by default parse number as Double, core will fail to start
object : TypeToken<Double>() {}.type,
JsonSerializer { src: Double?, _: Type?, _: JsonSerializationContext? ->
JsonPrimitive(
src?.toInt()
)
}
)
.create()
val serverList: Array<Any> =
Gson().fromJson(server, Array<Any>::class.java)
JsonUtil.fromJson(server, Array<Any>::class.java)

if (serverList.isNotEmpty()) {
var count = 0
for (srv in serverList.reversed()) {
val config = ServerConfig.create(EConfigType.CUSTOM)
config.fullConfig =
Gson().fromJson(Gson().toJson(srv), V2rayConfig::class.java)
JsonUtil.fromJson(JsonUtil.toJson(srv), V2rayConfig::class.java)
config.remarks = config.fullConfig?.remarks
?: ("%04d-".format(count + 1) + System.currentTimeMillis()
.toString())
config.subscriptionId = subid
val key = MmkvManager.encodeServerConfig("", config)
MmkvManager.encodeServerRaw(key, gson.toJson(srv))
MmkvManager.encodeServerRaw(key, JsonUtil.toJsonPretty(srv))
count += 1
}
return count
Expand All @@ -317,7 +304,7 @@ object AngConfigManager {
// For compatibility
val config = ServerConfig.create(EConfigType.CUSTOM)
config.subscriptionId = subid
config.fullConfig = Gson().fromJson(server, V2rayConfig::class.java)
config.fullConfig = JsonUtil.fromJson(server, V2rayConfig::class.java)
config.remarks = config.fullConfig?.remarks ?: System.currentTimeMillis().toString()
val key = MmkvManager.encodeServerConfig("", config)
MmkvManager.encodeServerRaw(key, server)
Expand Down
37 changes: 37 additions & 0 deletions app/src/main/kotlin/com/neko/v2ray/util/JsonUtil.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package com.neko.v2ray.util

import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.JsonPrimitive
import com.google.gson.JsonSerializationContext
import com.google.gson.JsonSerializer
import com.google.gson.reflect.TypeToken
import java.lang.reflect.Type

object JsonUtil {
private var gson = Gson()

fun toJson(src: Any?): String {
return gson.toJson(src)
}

fun <T> fromJson(json: String, cls: Class<T>): T {
return gson.fromJson(json, cls)
}

fun toJsonPretty(src: Any?): String {
val gsonPre = GsonBuilder()
.setPrettyPrinting()
.disableHtmlEscaping()
.registerTypeAdapter( // custom serialiser is needed here since JSON by default parse number as Double, core will fail to start
object : TypeToken<Double>() {}.type,
JsonSerializer { src: Double?, _: Type?, _: JsonSerializationContext? ->
JsonPrimitive(
src?.toInt()
)
}
)
.create()
return gsonPre.toJson(src)
}
}
40 changes: 20 additions & 20 deletions app/src/main/kotlin/com/neko/v2ray/util/MmkvManager.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.neko.v2ray.util

import com.google.gson.Gson

import com.tencent.mmkv.MMKV
import com.neko.v2ray.AppConfig.PREF_IS_BOOTED
import com.neko.v2ray.AppConfig.PREF_ROUTING_RULESET
Expand Down Expand Up @@ -49,15 +49,15 @@ object MmkvManager {
}

fun encodeServerList(serverList: MutableList<String>) {
mainStorage.encode(KEY_ANG_CONFIGS, Gson().toJson(serverList))
mainStorage.encode(KEY_ANG_CONFIGS, JsonUtil.toJson(serverList))
}

fun decodeServerList(): MutableList<String> {
val json = mainStorage.decodeString(KEY_ANG_CONFIGS)
return if (json.isNullOrBlank()) {
mutableListOf()
} else {
Gson().fromJson(json, Array<String>::class.java).toMutableList()
JsonUtil.fromJson(json, Array<String>::class.java).toMutableList()
}
}

Expand All @@ -69,7 +69,7 @@ object MmkvManager {
if (json.isNullOrBlank()) {
return null
}
return Gson().fromJson(json, ServerConfig::class.java)
return JsonUtil.fromJson(json, ServerConfig::class.java)
}

fun decodeProfileConfig(guid: String): ProfileItem? {
Expand All @@ -80,12 +80,12 @@ object MmkvManager {
if (json.isNullOrBlank()) {
return null
}
return Gson().fromJson(json, ProfileItem::class.java)
return JsonUtil.fromJson(json, ProfileItem::class.java)
}

fun encodeServerConfig(guid: String, config: ServerConfig): String {
val key = guid.ifBlank { Utils.getUuid() }
serverStorage.encode(key, Gson().toJson(config))
serverStorage.encode(key, JsonUtil.toJson(config))
val serverList = decodeServerList()
if (!serverList.contains(key)) {
serverList.add(0, key)
Expand All @@ -101,7 +101,7 @@ object MmkvManager {
server = config.getProxyOutbound()?.getServerAddress(),
serverPort = config.getProxyOutbound()?.getServerPort(),
)
profileStorage.encode(key, Gson().toJson(profile))
profileStorage.encode(key, JsonUtil.toJson(profile))
return key
}

Expand Down Expand Up @@ -141,7 +141,7 @@ object MmkvManager {
if (json.isNullOrBlank()) {
return null
}
return Gson().fromJson(json, ServerAffiliationInfo::class.java)
return JsonUtil.fromJson(json, ServerAffiliationInfo::class.java)
}

fun encodeServerTestDelayMillis(guid: String, testResult: Long) {
Expand All @@ -150,14 +150,14 @@ object MmkvManager {
}
val aff = decodeServerAffiliationInfo(guid) ?: ServerAffiliationInfo()
aff.testDelayMillis = testResult
serverAffStorage.encode(guid, Gson().toJson(aff))
serverAffStorage.encode(guid, JsonUtil.toJson(aff))
}

fun clearAllTestDelayResults(keys: List<String>?) {
keys?.forEach { key ->
decodeServerAffiliationInfo(key)?.let { aff ->
aff.testDelayMillis = 0
serverAffStorage.encode(key, Gson().toJson(aff))
serverAffStorage.encode(key, JsonUtil.toJson(aff))
}
}
}
Expand Down Expand Up @@ -217,7 +217,7 @@ object MmkvManager {
decodeSubsList().forEach { key ->
val json = subStorage.decodeString(key)
if (!json.isNullOrBlank()) {
subscriptions.add(Pair(key, Gson().fromJson(json, SubscriptionItem::class.java)))
subscriptions.add(Pair(key, JsonUtil.fromJson(json, SubscriptionItem::class.java)))
}
}
return subscriptions
Expand All @@ -234,7 +234,7 @@ object MmkvManager {

fun encodeSubscription(guid: String, subItem: SubscriptionItem) {
val key = guid.ifBlank { Utils.getUuid() }
subStorage.encode(key, Gson().toJson(subItem))
subStorage.encode(key, JsonUtil.toJson(subItem))

val subsList = decodeSubsList()
if (!subsList.contains(key)) {
Expand All @@ -245,19 +245,19 @@ object MmkvManager {

fun decodeSubscription(subscriptionId: String): SubscriptionItem? {
val json = subStorage.decodeString(subscriptionId) ?: return null
return Gson().fromJson(json, SubscriptionItem::class.java)
return JsonUtil.fromJson(json, SubscriptionItem::class.java)
}

fun encodeSubsList(subsList: MutableList<String>) {
mainStorage.encode(KEY_SUB_IDS, Gson().toJson(subsList))
mainStorage.encode(KEY_SUB_IDS, JsonUtil.toJson(subsList))
}

fun decodeSubsList(): MutableList<String> {
val json = mainStorage.decodeString(KEY_SUB_IDS)
return if (json.isNullOrBlank()) {
mutableListOf()
} else {
Gson().fromJson(json, Array<String>::class.java).toMutableList()
JsonUtil.fromJson(json, Array<String>::class.java).toMutableList()
}
}

Expand All @@ -270,7 +270,7 @@ object MmkvManager {
assetStorage.allKeys()?.forEach { key ->
val json = assetStorage.decodeString(key)
if (!json.isNullOrBlank()) {
assetUrlItems.add(Pair(key, Gson().fromJson(json, AssetUrlItem::class.java)))
assetUrlItems.add(Pair(key, JsonUtil.fromJson(json, AssetUrlItem::class.java)))
}
}
return assetUrlItems.sortedBy { (_, value) -> value.addedTime }
Expand All @@ -282,12 +282,12 @@ object MmkvManager {

fun encodeAsset(assetid: String, assetItem: AssetUrlItem) {
val key = assetid.ifBlank { Utils.getUuid() }
assetStorage.encode(key, Gson().toJson(assetItem))
assetStorage.encode(key, JsonUtil.toJson(assetItem))
}

fun decodeAsset(assetid: String): AssetUrlItem? {
val json = assetStorage.decodeString(assetid) ?: return null
return Gson().fromJson(json, AssetUrlItem::class.java)
return JsonUtil.fromJson(json, AssetUrlItem::class.java)
}

//endregion
Expand All @@ -297,14 +297,14 @@ object MmkvManager {
fun decodeRoutingRulesets(): MutableList<RulesetItem>? {
val ruleset = settingsStorage.decodeString(PREF_ROUTING_RULESET)
if (ruleset.isNullOrEmpty()) return null
return Gson().fromJson(ruleset, Array<RulesetItem>::class.java).toMutableList()
return JsonUtil.fromJson(ruleset, Array<RulesetItem>::class.java).toMutableList()
}

fun encodeRoutingRulesets(rulesetList: MutableList<RulesetItem>?) {
if (rulesetList.isNullOrEmpty())
settingsStorage.encode(PREF_ROUTING_RULESET, "")
else
settingsStorage.encode(PREF_ROUTING_RULESET, Gson().toJson(rulesetList))
settingsStorage.encode(PREF_ROUTING_RULESET, JsonUtil.toJson(rulesetList))
}

//endregion
Expand Down
5 changes: 2 additions & 3 deletions app/src/main/kotlin/com/neko/v2ray/util/PluginUtil.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package com.neko.v2ray.util
import android.content.Context
import android.os.SystemClock
import android.util.Log
import com.google.gson.Gson
import com.neko.v2ray.AppConfig.ANG_PACKAGE
import com.neko.v2ray.dto.EConfigType
import com.neko.v2ray.dto.ServerConfig
Expand Down Expand Up @@ -38,8 +37,8 @@ object PluginUtil {
Log.d(packageName, "runPlugin ${configFile.absolutePath}")

configFile.parentFile?.mkdirs()
configFile.writeText(Gson().toJson(hy2Config))
Log.d(packageName, Gson().toJson(hy2Config))
configFile.writeText(JsonUtil.toJson(hy2Config))
Log.d(packageName, JsonUtil.toJson(hy2Config))

runHy2(context, configFile)
}
Expand Down
5 changes: 2 additions & 3 deletions app/src/main/kotlin/com/neko/v2ray/util/SettingsManager.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package com.neko.v2ray.util

import android.content.Context
import android.text.TextUtils
import com.google.gson.Gsonl
import com.neko.v2ray.AppConfig
import com.neko.v2ray.dto.RulesetItem
import com.neko.v2ray.dto.ServerConfig
Expand Down Expand Up @@ -35,7 +34,7 @@ object SettingsManager {
return null
}

return Gson().fromJson(assets, Array<RulesetItem>::class.java).toMutableList()
return JsonUtil.fromJson(assets, Array<RulesetItem>::class.java).toMutableList()
}

fun resetRoutingRulesets(context: Context, index: Int) {
Expand All @@ -49,7 +48,7 @@ object SettingsManager {
}

try {
val rulesetList = Gson().fromJson(content, Array<RulesetItem>::class.java).toMutableList()
val rulesetList = JsonUtil.fromJson(content, Array<RulesetItem>::class.java).toMutableList()
if (rulesetList.isNullOrEmpty()) {
return false
}
Expand Down
Loading

0 comments on commit 35b3f0d

Please sign in to comment.