ConfigHelper.kt 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package com.cretin.translatetools.config
  2. import com.cretin.translatetools.entity.ConfigJson
  3. import com.cretin.translatetools.utils.GsonGet
  4. import org.apache.http.util.TextUtils
  5. import java.io.File
  6. object ConfigHelper {
  7. /**
  8. * 获取配置文件
  9. */
  10. private fun getConfigFile(): File? {
  11. return try {
  12. var jarPath = System.getProperty("java.class.path")
  13. jarPath = jarPath.substring(0, jarPath.lastIndexOf("/"))
  14. val file = File("$jarPath/cm_translate_v2.conf")
  15. if (!file.exists()) {
  16. file.createNewFile()
  17. }
  18. file
  19. } catch (e: Exception) {
  20. null
  21. }
  22. }
  23. fun getConfigHost(): String {
  24. if (Config.IS_DEBUG) {
  25. return Config.HOST
  26. }
  27. return getConfig().host
  28. }
  29. fun getConfigAdmin(): String {
  30. if (Config.IS_DEBUG) {
  31. return Config.HOST_ADMIN
  32. }
  33. return getConfig().admin
  34. }
  35. fun writeConfigClient(clientType: Int) {
  36. if (!Config.IS_DEBUG)
  37. getConfig()?.apply {
  38. this.clientType = clientType
  39. getConfigFile()?.writeText(GsonGet.getGson().toJson(this))
  40. }
  41. }
  42. fun writeConfigVersion(version: String) {
  43. if (!Config.IS_DEBUG)
  44. getConfig()?.apply {
  45. this.version = version
  46. getConfigFile()?.writeText(GsonGet.getGson().toJson(this))
  47. }
  48. }
  49. fun writeConfigToken(token: String) {
  50. if (!Config.IS_DEBUG)
  51. getConfig()?.apply {
  52. this.token = token
  53. getConfigFile()?.writeText(GsonGet.getGson().toJson(this))
  54. }
  55. }
  56. fun writeConfigRootPath(rootPath: String) {
  57. if (!Config.IS_DEBUG)
  58. getConfig()?.apply {
  59. this.rootPath = rootPath
  60. getConfigFile()?.writeText(GsonGet.getGson().toJson(this))
  61. }
  62. }
  63. /**
  64. * 获取配置
  65. */
  66. fun getConfig(): ConfigJson {
  67. if (!Config.IS_DEBUG) {
  68. val file = getConfigFile()
  69. val content = file?.readText() ?: ""
  70. return if (TextUtils.isEmpty(content)) {
  71. ConfigJson.createNew()
  72. } else {
  73. try {
  74. GsonGet.getGson().fromJson(content, ConfigJson::class.java)
  75. } catch (e: Throwable) {
  76. ConfigJson.createNew()
  77. }
  78. }
  79. } else {
  80. return ConfigJson(1, "/Users/cretin/Downloads/ios_translate/zh-Hans.lproj", "43822f8e981141ec9bf322f5aa6bbacb")
  81. }
  82. }
  83. }