1
0

inbound_settings_clients.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package service
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "strings"
  6. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  7. "github.com/mhsanaei/3x-ui/v3/internal/util/common"
  8. )
  9. func ParseInboundSettingsClients(settings string) ([]model.Client, error) {
  10. trimmed := strings.TrimSpace(settings)
  11. if trimmed == "" || trimmed == "null" {
  12. return nil, common.NewError("inbound settings is empty")
  13. }
  14. var payload struct {
  15. Clients json.RawMessage `json:"clients"`
  16. }
  17. if err := json.Unmarshal([]byte(trimmed), &payload); err != nil {
  18. return nil, err
  19. }
  20. if len(payload.Clients) == 0 || string(payload.Clients) == "null" {
  21. return nil, nil
  22. }
  23. var clients []model.Client
  24. if err := json.Unmarshal(payload.Clients, &clients); err != nil {
  25. return nil, err
  26. }
  27. return clients, nil
  28. }
  29. // settingsEntriesToClients decodes the wire entries a caller has already
  30. // stamped, so a delta carries the persisted created_at / updated_at / subId
  31. // rather than the pre-stamp values the request was parsed into.
  32. func settingsEntriesToClients(entries []any) ([]model.Client, error) {
  33. if len(entries) == 0 {
  34. return nil, nil
  35. }
  36. raw, err := json.Marshal(entries)
  37. if err != nil {
  38. return nil, err
  39. }
  40. var clients []model.Client
  41. if err := json.Unmarshal(raw, &clients); err != nil {
  42. return nil, err
  43. }
  44. return clients, nil
  45. }
  46. // normalizeLegacyClientSettings rewrites settings whose clients still carry the
  47. // string numbers of a v2.x export, so parsing and storage see a single shape.
  48. func normalizeLegacyClientSettings(inbound *model.Inbound) {
  49. dec := json.NewDecoder(bytes.NewReader([]byte(inbound.Settings)))
  50. dec.UseNumber()
  51. var settings map[string]any
  52. if err := dec.Decode(&settings); err != nil {
  53. return
  54. }
  55. clients, _ := settings["clients"].([]any)
  56. changed := false
  57. for _, raw := range clients {
  58. if obj, ok := raw.(map[string]any); ok && model.NormalizeLegacyClientFields(obj) {
  59. changed = true
  60. }
  61. }
  62. if !changed {
  63. return
  64. }
  65. if out, err := json.MarshalIndent(settings, "", " "); err == nil {
  66. inbound.Settings = string(out)
  67. }
  68. }