console_migrate.go 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // 用于迁移检测的旧键,该文件下个版本会删除
  2. package controller
  3. import (
  4. "encoding/json"
  5. "net/http"
  6. "one-api/common"
  7. "one-api/model"
  8. "github.com/gin-gonic/gin"
  9. )
  10. // MigrateConsoleSetting 迁移旧的控制台相关配置到 console_setting.*
  11. func MigrateConsoleSetting(c *gin.Context) {
  12. // 读取全部 option
  13. opts, err := model.AllOption()
  14. if err != nil {
  15. c.JSON(http.StatusInternalServerError, gin.H{"success": false, "message": err.Error()})
  16. return
  17. }
  18. // 建立 map
  19. valMap := map[string]string{}
  20. for _, o := range opts {
  21. valMap[o.Key] = o.Value
  22. }
  23. // 处理 APIInfo
  24. if v := valMap["ApiInfo"]; v != "" {
  25. var arr []map[string]interface{}
  26. if err := json.Unmarshal([]byte(v), &arr); err == nil {
  27. if len(arr) > 50 {
  28. arr = arr[:50]
  29. }
  30. bytes, _ := json.Marshal(arr)
  31. model.UpdateOption("console_setting.api_info", string(bytes))
  32. }
  33. model.UpdateOption("ApiInfo", "")
  34. }
  35. // Announcements 直接搬
  36. if v := valMap["Announcements"]; v != "" {
  37. model.UpdateOption("console_setting.announcements", v)
  38. model.UpdateOption("Announcements", "")
  39. }
  40. // FAQ 转换
  41. if v := valMap["FAQ"]; v != "" {
  42. var arr []map[string]interface{}
  43. if err := json.Unmarshal([]byte(v), &arr); err == nil {
  44. out := []map[string]interface{}{}
  45. for _, item := range arr {
  46. q, _ := item["question"].(string)
  47. if q == "" {
  48. q, _ = item["title"].(string)
  49. }
  50. a, _ := item["answer"].(string)
  51. if a == "" {
  52. a, _ = item["content"].(string)
  53. }
  54. if q != "" && a != "" {
  55. out = append(out, map[string]interface{}{"question": q, "answer": a})
  56. }
  57. }
  58. if len(out) > 50 {
  59. out = out[:50]
  60. }
  61. bytes, _ := json.Marshal(out)
  62. model.UpdateOption("console_setting.faq", string(bytes))
  63. }
  64. model.UpdateOption("FAQ", "")
  65. }
  66. // Uptime
  67. if v := valMap["UptimeKumaUrl"]; v != "" {
  68. model.UpdateOption("console_setting.uptime_kuma_url", v)
  69. model.UpdateOption("UptimeKumaUrl", "")
  70. }
  71. if v := valMap["UptimeKumaSlug"]; v != "" {
  72. model.UpdateOption("console_setting.uptime_kuma_slug", v)
  73. model.UpdateOption("UptimeKumaSlug", "")
  74. }
  75. // 删除旧键记录
  76. oldKeys := []string{"ApiInfo", "Announcements", "FAQ", "UptimeKumaUrl", "UptimeKumaSlug"}
  77. model.DB.Where("key IN ?", oldKeys).Delete(&model.Option{})
  78. // 重新加载 OptionMap
  79. model.InitOptionMap()
  80. common.SysLog("console setting migrated")
  81. c.JSON(http.StatusOK, gin.H{"success": true, "message": "migrated"})
  82. }