model.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641
  1. // Package model defines the database models and data structures used by the 3x-ui panel.
  2. package model
  3. import (
  4. "bytes"
  5. "encoding/json"
  6. "fmt"
  7. "strings"
  8. "github.com/mhsanaei/3x-ui/v3/util/json_util"
  9. "github.com/mhsanaei/3x-ui/v3/xray"
  10. )
  11. // Protocol represents the protocol type for Xray inbounds.
  12. type Protocol string
  13. // Protocol constants for different Xray inbound protocols.
  14. // Hysteria v2 is not a distinct protocol — it is plain "hysteria"
  15. // with streamSettings.version = 2. The share-link URI scheme
  16. // "hysteria2://" is independent of this and is still emitted by the
  17. // link generator when the stream version is 2.
  18. const (
  19. VMESS Protocol = "vmess"
  20. VLESS Protocol = "vless"
  21. Tunnel Protocol = "tunnel"
  22. HTTP Protocol = "http"
  23. Trojan Protocol = "trojan"
  24. Shadowsocks Protocol = "shadowsocks"
  25. Mixed Protocol = "mixed"
  26. WireGuard Protocol = "wireguard"
  27. Hysteria Protocol = "hysteria"
  28. )
  29. // User represents a user account in the 3x-ui panel.
  30. type User struct {
  31. Id int `json:"id" gorm:"primaryKey;autoIncrement"`
  32. Username string `json:"username"`
  33. Password string `json:"password"`
  34. LoginEpoch int64 `json:"-" gorm:"default:0"`
  35. }
  36. // Inbound represents an Xray inbound configuration with traffic statistics and settings.
  37. type Inbound struct {
  38. Id int `json:"id" form:"id" gorm:"primaryKey;autoIncrement"` // Unique identifier
  39. UserId int `json:"-"` // Associated user ID
  40. Up int64 `json:"up" form:"up"` // Upload traffic in bytes
  41. Down int64 `json:"down" form:"down"` // Download traffic in bytes
  42. Total int64 `json:"total" form:"total"` // Total traffic limit in bytes
  43. Remark string `json:"remark" form:"remark"` // Human-readable remark
  44. Enable bool `json:"enable" form:"enable" gorm:"index:idx_enable_traffic_reset,priority:1"` // Whether the inbound is enabled
  45. ExpiryTime int64 `json:"expiryTime" form:"expiryTime"` // Expiration timestamp
  46. TrafficReset string `json:"trafficReset" form:"trafficReset" gorm:"default:never;index:idx_enable_traffic_reset,priority:2" validate:"omitempty,oneof=never hourly daily weekly monthly"` // Traffic reset schedule
  47. LastTrafficResetTime int64 `json:"lastTrafficResetTime" form:"lastTrafficResetTime" gorm:"default:0"` // Last traffic reset timestamp
  48. ClientStats []xray.ClientTraffic `gorm:"foreignKey:InboundId;references:Id" json:"clientStats" form:"clientStats"` // Client traffic statistics
  49. // Xray configuration fields
  50. Listen string `json:"listen" form:"listen"`
  51. Port int `json:"port" form:"port" validate:"gte=1,lte=65535"`
  52. Protocol Protocol `json:"protocol" form:"protocol" validate:"required,oneof=vmess vless trojan shadowsocks wireguard hysteria http mixed tunnel"`
  53. Settings string `json:"settings" form:"settings"`
  54. StreamSettings string `json:"streamSettings" form:"streamSettings"`
  55. Tag string `json:"tag" form:"tag" gorm:"unique"`
  56. Sniffing string `json:"sniffing" form:"sniffing"`
  57. NodeID *int `json:"nodeId,omitempty" form:"nodeId" gorm:"index"`
  58. // FallbackParent is populated by the API layer when this inbound is
  59. // attached as a fallback child of a VLESS/Trojan TCP-TLS master.
  60. // The frontend uses it to rewrite client-share links so they advertise
  61. // the master's externally reachable endpoint instead of the child's
  62. // loopback listen. Not persisted.
  63. FallbackParent *FallbackParentInfo `json:"fallbackParent,omitempty" gorm:"-"`
  64. }
  65. // FallbackParentInfo carries everything the frontend needs to rewrite a
  66. // child inbound's client link: where to connect (the master's address
  67. // and port) and which path matched on the master's fallbacks array.
  68. // The frontend already has the master inbound in its dbInbounds list,
  69. // so we only ship identifiers + the match path here.
  70. type FallbackParentInfo struct {
  71. MasterId int `json:"masterId"`
  72. Path string `json:"path,omitempty"`
  73. }
  74. // OutboundTraffics tracks traffic statistics for Xray outbound connections.
  75. type OutboundTraffics struct {
  76. Id int `json:"id" form:"id" gorm:"primaryKey;autoIncrement"`
  77. Tag string `json:"tag" form:"tag" gorm:"unique"`
  78. Up int64 `json:"up" form:"up" gorm:"default:0"`
  79. Down int64 `json:"down" form:"down" gorm:"default:0"`
  80. Total int64 `json:"total" form:"total" gorm:"default:0"`
  81. }
  82. // InboundClientIps stores IP addresses associated with inbound clients for access control.
  83. type InboundClientIps struct {
  84. Id int `json:"id" gorm:"primaryKey;autoIncrement"`
  85. ClientEmail string `json:"clientEmail" form:"clientEmail" gorm:"unique"`
  86. Ips string `json:"ips" form:"ips"`
  87. }
  88. // MarshalJSON emits the Ips column as a real JSON array instead of an escaped
  89. // JSON-text string. Empty or unparseable storage renders as null so API
  90. // consumers don't have to special-case the legacy double-encoded shape.
  91. func (ic InboundClientIps) MarshalJSON() ([]byte, error) {
  92. type alias InboundClientIps
  93. return json.Marshal(struct {
  94. alias
  95. Ips json.RawMessage `json:"ips"`
  96. }{
  97. alias: alias(ic),
  98. Ips: jsonStringFieldToRaw(ic.Ips),
  99. })
  100. }
  101. // UnmarshalJSON accepts ips as either a JSON array (modern shape) or a
  102. // JSON-encoded string (legacy shape), normalising back to the JSON-text the
  103. // column stores.
  104. func (ic *InboundClientIps) UnmarshalJSON(data []byte) error {
  105. type alias InboundClientIps
  106. aux := struct {
  107. *alias
  108. Ips json.RawMessage `json:"ips"`
  109. }{
  110. alias: (*alias)(ic),
  111. }
  112. if err := json.Unmarshal(data, &aux); err != nil {
  113. return err
  114. }
  115. ic.Ips = jsonStringFieldFromRaw(aux.Ips)
  116. return nil
  117. }
  118. // HistoryOfSeeders tracks which database seeders have been executed to prevent re-running.
  119. type HistoryOfSeeders struct {
  120. Id int `json:"id" gorm:"primaryKey;autoIncrement"`
  121. SeederName string `json:"seederName"`
  122. }
  123. type ApiToken struct {
  124. Id int `json:"id" gorm:"primaryKey;autoIncrement"`
  125. Name string `json:"name" gorm:"uniqueIndex;not null"`
  126. Token string `json:"token" gorm:"not null"`
  127. Enabled bool `json:"enabled" gorm:"default:true"`
  128. CreatedAt int64 `json:"createdAt" gorm:"autoCreateTime:milli"`
  129. }
  130. // MarshalJSON emits settings, streamSettings, and sniffing as nested JSON
  131. // objects rather than escaped strings, so API consumers don't need to JSON.parse
  132. // a string inside a string. Empty fields render as null; fields whose stored
  133. // text isn't valid JSON fall back to a JSON-encoded string so no data is lost.
  134. func (i Inbound) MarshalJSON() ([]byte, error) {
  135. type alias Inbound
  136. return json.Marshal(struct {
  137. alias
  138. Settings json.RawMessage `json:"settings"`
  139. StreamSettings json.RawMessage `json:"streamSettings"`
  140. Sniffing json.RawMessage `json:"sniffing"`
  141. }{
  142. alias: alias(i),
  143. Settings: jsonStringFieldToRaw(i.Settings),
  144. StreamSettings: jsonStringFieldToRaw(i.StreamSettings),
  145. Sniffing: jsonStringFieldToRaw(i.Sniffing),
  146. })
  147. }
  148. // UnmarshalJSON accepts settings, streamSettings, and sniffing as either a raw
  149. // JSON object/array (the modern shape MarshalJSON emits) or a JSON-encoded
  150. // string (the legacy shape). Either form is normalised back to the JSON-text
  151. // string the DB column stores.
  152. func (i *Inbound) UnmarshalJSON(data []byte) error {
  153. type alias Inbound
  154. aux := struct {
  155. *alias
  156. Settings json.RawMessage `json:"settings"`
  157. StreamSettings json.RawMessage `json:"streamSettings"`
  158. Sniffing json.RawMessage `json:"sniffing"`
  159. }{
  160. alias: (*alias)(i),
  161. }
  162. if err := json.Unmarshal(data, &aux); err != nil {
  163. return err
  164. }
  165. i.Settings = jsonStringFieldFromRaw(aux.Settings)
  166. i.StreamSettings = jsonStringFieldFromRaw(aux.StreamSettings)
  167. i.Sniffing = jsonStringFieldFromRaw(aux.Sniffing)
  168. return nil
  169. }
  170. func jsonStringFieldToRaw(s string) json.RawMessage {
  171. trimmed := strings.TrimSpace(s)
  172. if trimmed == "" {
  173. return json.RawMessage("null")
  174. }
  175. if json.Valid([]byte(trimmed)) {
  176. return json.RawMessage(trimmed)
  177. }
  178. b, _ := json.Marshal(s)
  179. return b
  180. }
  181. func jsonStringFieldFromRaw(r json.RawMessage) string {
  182. trimmed := bytes.TrimSpace(r)
  183. if len(trimmed) == 0 || bytes.Equal(trimmed, []byte("null")) {
  184. return ""
  185. }
  186. if trimmed[0] == '"' {
  187. var s string
  188. if err := json.Unmarshal(trimmed, &s); err == nil {
  189. return s
  190. }
  191. }
  192. return string(trimmed)
  193. }
  194. // GenXrayInboundConfig generates an Xray inbound configuration from the Inbound model.
  195. func (i *Inbound) GenXrayInboundConfig() *xray.InboundConfig {
  196. listen := i.Listen
  197. if listen == "" {
  198. listen = "0.0.0.0"
  199. }
  200. listen = fmt.Sprintf("\"%v\"", listen)
  201. protocol := string(i.Protocol)
  202. settings := i.Settings
  203. if i.Protocol == Shadowsocks {
  204. if healed, ok := HealShadowsocksClientMethods(settings); ok {
  205. settings = healed
  206. }
  207. }
  208. return &xray.InboundConfig{
  209. Listen: json_util.RawMessage(listen),
  210. Port: i.Port,
  211. Protocol: protocol,
  212. Settings: json_util.RawMessage(settings),
  213. StreamSettings: json_util.RawMessage(i.StreamSettings),
  214. Tag: i.Tag,
  215. Sniffing: json_util.RawMessage(i.Sniffing),
  216. }
  217. }
  218. // HealShadowsocksClientMethods normalises the per-client `method` field
  219. // on a shadowsocks inbound's settings JSON before it leaves for xray-core:
  220. // - Legacy ciphers (aes-*, chacha20-*): every client must carry a
  221. // per-user `method` matching the inbound's top-level method, otherwise
  222. // xray fails with "unsupported cipher method:".
  223. // - Shadowsocks 2022 (2022-blake3-*): xray's multi-user code rejects the
  224. // inbound with "users must have empty method" when a client carries
  225. // one — strip stale entries left over from a switch off a legacy
  226. // cipher.
  227. // Returns the rewritten settings string and true when anything changed.
  228. func HealShadowsocksClientMethods(settings string) (string, bool) {
  229. if settings == "" {
  230. return settings, false
  231. }
  232. var parsed map[string]any
  233. if err := json.Unmarshal([]byte(settings), &parsed); err != nil {
  234. return settings, false
  235. }
  236. method, _ := parsed["method"].(string)
  237. clients, ok := parsed["clients"].([]any)
  238. if !ok {
  239. return settings, false
  240. }
  241. is2022 := strings.HasPrefix(method, "2022-blake3-")
  242. changed := false
  243. for i := range clients {
  244. cm, ok := clients[i].(map[string]any)
  245. if !ok {
  246. continue
  247. }
  248. if is2022 {
  249. if _, hasKey := cm["method"]; hasKey {
  250. delete(cm, "method")
  251. clients[i] = cm
  252. changed = true
  253. }
  254. continue
  255. }
  256. if method == "" {
  257. continue
  258. }
  259. existing, _ := cm["method"].(string)
  260. if existing == method {
  261. continue
  262. }
  263. cm["method"] = method
  264. clients[i] = cm
  265. changed = true
  266. }
  267. if !changed {
  268. return settings, false
  269. }
  270. out, err := json.MarshalIndent(parsed, "", " ")
  271. if err != nil {
  272. return settings, false
  273. }
  274. return string(out), true
  275. }
  276. // Setting stores key-value configuration settings for the 3x-ui panel.
  277. type Setting struct {
  278. Id int `json:"id" form:"id" gorm:"primaryKey;autoIncrement"`
  279. Key string `json:"key" form:"key"`
  280. Value string `json:"value" form:"value"`
  281. }
  282. // Node represents a remote 3x-ui panel registered with the central panel.
  283. // The central panel polls each node's existing /panel/api/server/status
  284. // endpoint over HTTP using the per-node ApiToken to populate the runtime
  285. // status fields below.
  286. type Node struct {
  287. Id int `json:"id" form:"id" gorm:"primaryKey;autoIncrement"`
  288. Name string `json:"name" form:"name" gorm:"uniqueIndex" validate:"required"`
  289. Remark string `json:"remark" form:"remark"`
  290. Scheme string `json:"scheme" form:"scheme" validate:"omitempty,oneof=http https"`
  291. Address string `json:"address" form:"address" validate:"required"`
  292. Port int `json:"port" form:"port" validate:"gte=1,lte=65535"`
  293. BasePath string `json:"basePath" form:"basePath"`
  294. ApiToken string `json:"apiToken" form:"apiToken" validate:"required"`
  295. Enable bool `json:"enable" form:"enable" gorm:"default:true"`
  296. AllowPrivateAddress bool `json:"allowPrivateAddress" form:"allowPrivateAddress" gorm:"default:false"`
  297. // Heartbeat-updated fields. UpdatedAt advances on every probe even when
  298. // the row is otherwise unchanged so the UI's "last seen" tooltip is
  299. // truthful without us having to read LastHeartbeat separately.
  300. Status string `json:"status" gorm:"default:unknown"` // online|offline|unknown
  301. LastHeartbeat int64 `json:"lastHeartbeat"` // unix seconds, 0 = never
  302. LatencyMs int `json:"latencyMs"`
  303. XrayVersion string `json:"xrayVersion"`
  304. PanelVersion string `json:"panelVersion" gorm:"column:panel_version"`
  305. CpuPct float64 `json:"cpuPct"`
  306. MemPct float64 `json:"memPct"`
  307. UptimeSecs uint64 `json:"uptimeSecs"`
  308. LastError string `json:"lastError"`
  309. InboundCount int `json:"inboundCount" gorm:"-"`
  310. ClientCount int `json:"clientCount" gorm:"-"`
  311. OnlineCount int `json:"onlineCount" gorm:"-"`
  312. DepletedCount int `json:"depletedCount" gorm:"-"`
  313. CreatedAt int64 `json:"createdAt" gorm:"autoCreateTime:milli"`
  314. UpdatedAt int64 `json:"updatedAt" gorm:"autoUpdateTime:milli"`
  315. }
  316. type CustomGeoResource struct {
  317. Id int `json:"id" gorm:"primaryKey;autoIncrement"`
  318. Type string `json:"type" gorm:"not null;uniqueIndex:idx_custom_geo_type_alias;column:geo_type"`
  319. Alias string `json:"alias" gorm:"not null;uniqueIndex:idx_custom_geo_type_alias"`
  320. Url string `json:"url" gorm:"not null"`
  321. LocalPath string `json:"localPath" gorm:"column:local_path"`
  322. LastUpdatedAt int64 `json:"lastUpdatedAt" gorm:"default:0;column:last_updated_at"`
  323. LastModified string `json:"lastModified" gorm:"column:last_modified"`
  324. CreatedAt int64 `json:"createdAt" gorm:"autoCreateTime:milli;column:created_at"`
  325. UpdatedAt int64 `json:"updatedAt" gorm:"autoUpdateTime:milli;column:updated_at"`
  326. }
  327. type ClientReverse struct {
  328. Tag string `json:"tag"`
  329. }
  330. // Client represents a client configuration for Xray inbounds with traffic limits and settings.
  331. type Client struct {
  332. ID string `json:"id,omitempty"` // Unique client identifier
  333. Security string `json:"security"` // Security method (e.g., "auto", "aes-128-gcm")
  334. Password string `json:"password,omitempty"` // Client password
  335. Flow string `json:"flow,omitempty"` // Flow control (XTLS)
  336. Reverse *ClientReverse `json:"reverse,omitempty"` // VLESS simple reverse proxy settings
  337. Auth string `json:"auth,omitempty"` // Auth password (Hysteria)
  338. Email string `json:"email"` // Client email identifier
  339. LimitIP int `json:"limitIp"` // IP limit for this client
  340. TotalGB int64 `json:"totalGB" form:"totalGB"` // Total traffic limit in GB
  341. ExpiryTime int64 `json:"expiryTime" form:"expiryTime"` // Expiration timestamp
  342. Enable bool `json:"enable" form:"enable"` // Whether the client is enabled
  343. TgID int64 `json:"tgId" form:"tgId"` // Telegram user ID for notifications
  344. SubID string `json:"subId" form:"subId"` // Subscription identifier
  345. Comment string `json:"comment" form:"comment"` // Client comment
  346. Reset int `json:"reset" form:"reset"` // Reset period in days
  347. CreatedAt int64 `json:"created_at,omitempty"` // Creation timestamp
  348. UpdatedAt int64 `json:"updated_at,omitempty"` // Last update timestamp
  349. }
  350. type ClientRecord struct {
  351. Id int `json:"id" gorm:"primaryKey;autoIncrement"`
  352. Email string `json:"email" gorm:"uniqueIndex;not null"`
  353. SubID string `json:"subId" gorm:"index;column:sub_id"`
  354. UUID string `json:"uuid" gorm:"column:uuid"`
  355. Password string `json:"password"`
  356. Auth string `json:"auth"`
  357. Flow string `json:"flow"`
  358. Security string `json:"security"`
  359. Reverse string `json:"reverse" gorm:"column:reverse"`
  360. LimitIP int `json:"limitIp" gorm:"column:limit_ip"`
  361. TotalGB int64 `json:"totalGB" gorm:"column:total_gb"`
  362. ExpiryTime int64 `json:"expiryTime" gorm:"column:expiry_time"`
  363. Enable bool `json:"enable" gorm:"default:true"`
  364. TgID int64 `json:"tgId" gorm:"column:tg_id"`
  365. Comment string `json:"comment"`
  366. Reset int `json:"reset" gorm:"default:0"`
  367. CreatedAt int64 `json:"createdAt" gorm:"autoCreateTime:milli"`
  368. UpdatedAt int64 `json:"updatedAt" gorm:"autoUpdateTime:milli"`
  369. }
  370. func (ClientRecord) TableName() string { return "clients" }
  371. // MarshalJSON emits the reverse column as a nested JSON object rather than an
  372. // escaped JSON-text string, matching the same convention Inbound uses for its
  373. // JSON-text columns. Empty storage renders as null.
  374. func (r ClientRecord) MarshalJSON() ([]byte, error) {
  375. type alias ClientRecord
  376. return json.Marshal(struct {
  377. alias
  378. Reverse json.RawMessage `json:"reverse"`
  379. }{
  380. alias: alias(r),
  381. Reverse: jsonStringFieldToRaw(r.Reverse),
  382. })
  383. }
  384. // UnmarshalJSON accepts reverse as either a JSON object (modern shape) or a
  385. // JSON-encoded string (legacy shape).
  386. func (r *ClientRecord) UnmarshalJSON(data []byte) error {
  387. type alias ClientRecord
  388. aux := struct {
  389. *alias
  390. Reverse json.RawMessage `json:"reverse"`
  391. }{
  392. alias: (*alias)(r),
  393. }
  394. if err := json.Unmarshal(data, &aux); err != nil {
  395. return err
  396. }
  397. r.Reverse = jsonStringFieldFromRaw(aux.Reverse)
  398. return nil
  399. }
  400. type ClientInbound struct {
  401. ClientId int `json:"clientId" gorm:"primaryKey;column:client_id;index"`
  402. InboundId int `json:"inboundId" gorm:"primaryKey;column:inbound_id;index"`
  403. FlowOverride string `json:"flowOverride" gorm:"column:flow_override"`
  404. CreatedAt int64 `json:"createdAt" gorm:"autoCreateTime:milli"`
  405. }
  406. func (ClientInbound) TableName() string { return "client_inbounds" }
  407. // InboundFallback is one routing rule on a master inbound's
  408. // settings.fallbacks array. The master is always a VLESS or Trojan
  409. // inbound on TCP transport with TLS or Reality. The child is any other
  410. // inbound — its listen+port becomes the fallback dest, with optional
  411. // SNI/ALPN/path match criteria pulled from the same row.
  412. type InboundFallback struct {
  413. Id int `json:"id" gorm:"primaryKey;autoIncrement"`
  414. MasterId int `json:"masterId" gorm:"index;not null;column:master_id"`
  415. ChildId int `json:"childId" gorm:"index;not null;column:child_id"`
  416. Name string `json:"name"`
  417. Alpn string `json:"alpn"`
  418. Path string `json:"path"`
  419. Xver int `json:"xver"`
  420. SortOrder int `json:"sortOrder" gorm:"default:0;column:sort_order"`
  421. }
  422. func (InboundFallback) TableName() string { return "inbound_fallbacks" }
  423. func (c *Client) ToRecord() *ClientRecord {
  424. rec := &ClientRecord{
  425. Email: c.Email,
  426. SubID: c.SubID,
  427. UUID: c.ID,
  428. Password: c.Password,
  429. Auth: c.Auth,
  430. Flow: c.Flow,
  431. Security: c.Security,
  432. LimitIP: c.LimitIP,
  433. TotalGB: c.TotalGB,
  434. ExpiryTime: c.ExpiryTime,
  435. Enable: c.Enable,
  436. TgID: c.TgID,
  437. Comment: c.Comment,
  438. Reset: c.Reset,
  439. CreatedAt: c.CreatedAt,
  440. UpdatedAt: c.UpdatedAt,
  441. }
  442. if c.Reverse != nil {
  443. if b, err := json.Marshal(c.Reverse); err == nil {
  444. rec.Reverse = string(b)
  445. }
  446. }
  447. return rec
  448. }
  449. func (r *ClientRecord) ToClient() *Client {
  450. c := &Client{
  451. ID: r.UUID,
  452. Email: r.Email,
  453. SubID: r.SubID,
  454. Password: r.Password,
  455. Auth: r.Auth,
  456. Flow: r.Flow,
  457. Security: r.Security,
  458. LimitIP: r.LimitIP,
  459. TotalGB: r.TotalGB,
  460. ExpiryTime: r.ExpiryTime,
  461. Enable: r.Enable,
  462. TgID: r.TgID,
  463. Comment: r.Comment,
  464. Reset: r.Reset,
  465. CreatedAt: r.CreatedAt,
  466. UpdatedAt: r.UpdatedAt,
  467. }
  468. if r.Reverse != "" {
  469. var rev ClientReverse
  470. if err := json.Unmarshal([]byte(r.Reverse), &rev); err == nil {
  471. c.Reverse = &rev
  472. }
  473. }
  474. return c
  475. }
  476. type ClientMergeConflict struct {
  477. Field string
  478. Old any
  479. New any
  480. Kept any
  481. }
  482. func MergeClientRecord(existing *ClientRecord, incoming *ClientRecord) []ClientMergeConflict {
  483. var conflicts []ClientMergeConflict
  484. keep := func(field string, oldV, newV, kept any) {
  485. conflicts = append(conflicts, ClientMergeConflict{Field: field, Old: oldV, New: newV, Kept: kept})
  486. }
  487. const redacted = "<redacted>"
  488. keepSecret := func(field string) {
  489. conflicts = append(conflicts, ClientMergeConflict{Field: field, Old: redacted, New: redacted, Kept: redacted})
  490. }
  491. incomingNewer := incoming.UpdatedAt > existing.UpdatedAt ||
  492. (incoming.UpdatedAt == existing.UpdatedAt && incoming.CreatedAt > existing.CreatedAt)
  493. if existing.UUID != incoming.UUID && incoming.UUID != "" {
  494. if incomingNewer || existing.UUID == "" {
  495. existing.UUID = incoming.UUID
  496. }
  497. keepSecret("uuid")
  498. }
  499. if existing.Password != incoming.Password && incoming.Password != "" {
  500. if incomingNewer || existing.Password == "" {
  501. existing.Password = incoming.Password
  502. keepSecret("password")
  503. }
  504. }
  505. if existing.Auth != incoming.Auth && incoming.Auth != "" {
  506. if incomingNewer || existing.Auth == "" {
  507. existing.Auth = incoming.Auth
  508. keepSecret("auth")
  509. }
  510. }
  511. if existing.Flow != incoming.Flow && incoming.Flow != "" {
  512. if incomingNewer || existing.Flow == "" {
  513. keep("flow", existing.Flow, incoming.Flow, incoming.Flow)
  514. existing.Flow = incoming.Flow
  515. }
  516. }
  517. if existing.Security != incoming.Security && incoming.Security != "" {
  518. if incomingNewer || existing.Security == "" {
  519. keep("security", existing.Security, incoming.Security, incoming.Security)
  520. existing.Security = incoming.Security
  521. }
  522. }
  523. if existing.SubID != incoming.SubID && incoming.SubID != "" {
  524. if incomingNewer || existing.SubID == "" {
  525. existing.SubID = incoming.SubID
  526. keepSecret("subId")
  527. }
  528. }
  529. if existing.TotalGB != incoming.TotalGB {
  530. picked := existing.TotalGB
  531. if existing.TotalGB == 0 || (incoming.TotalGB != 0 && incoming.TotalGB > existing.TotalGB) {
  532. picked = incoming.TotalGB
  533. }
  534. if picked != existing.TotalGB {
  535. keep("totalGB", existing.TotalGB, incoming.TotalGB, picked)
  536. existing.TotalGB = picked
  537. }
  538. }
  539. if existing.ExpiryTime != incoming.ExpiryTime {
  540. picked := existing.ExpiryTime
  541. if existing.ExpiryTime == 0 || (incoming.ExpiryTime != 0 && incoming.ExpiryTime > existing.ExpiryTime) {
  542. picked = incoming.ExpiryTime
  543. }
  544. if picked != existing.ExpiryTime {
  545. keep("expiryTime", existing.ExpiryTime, incoming.ExpiryTime, picked)
  546. existing.ExpiryTime = picked
  547. }
  548. }
  549. if existing.LimitIP != incoming.LimitIP && incoming.LimitIP != 0 {
  550. picked := existing.LimitIP
  551. if existing.LimitIP == 0 || incoming.LimitIP > existing.LimitIP {
  552. picked = incoming.LimitIP
  553. }
  554. if picked != existing.LimitIP {
  555. keep("limitIp", existing.LimitIP, incoming.LimitIP, picked)
  556. existing.LimitIP = picked
  557. }
  558. }
  559. if existing.TgID != incoming.TgID && incoming.TgID != 0 {
  560. if incomingNewer || existing.TgID == 0 {
  561. keep("tgId", existing.TgID, incoming.TgID, incoming.TgID)
  562. existing.TgID = incoming.TgID
  563. }
  564. }
  565. if existing.Reset != incoming.Reset && incoming.Reset != 0 {
  566. if incomingNewer || existing.Reset == 0 {
  567. keep("reset", existing.Reset, incoming.Reset, incoming.Reset)
  568. existing.Reset = incoming.Reset
  569. }
  570. }
  571. if existing.Reverse != incoming.Reverse && incoming.Reverse != "" {
  572. if incomingNewer || existing.Reverse == "" {
  573. keep("reverse", existing.Reverse, incoming.Reverse, incoming.Reverse)
  574. existing.Reverse = incoming.Reverse
  575. }
  576. }
  577. if existing.Comment != incoming.Comment && incoming.Comment != "" {
  578. if incomingNewer || existing.Comment == "" {
  579. keep("comment", existing.Comment, incoming.Comment, incoming.Comment)
  580. existing.Comment = incoming.Comment
  581. }
  582. }
  583. if existing.Enable != incoming.Enable {
  584. if incoming.Enable {
  585. if !existing.Enable {
  586. keep("enable", existing.Enable, incoming.Enable, true)
  587. existing.Enable = true
  588. }
  589. }
  590. }
  591. if incoming.CreatedAt != 0 && (existing.CreatedAt == 0 || incoming.CreatedAt < existing.CreatedAt) {
  592. existing.CreatedAt = incoming.CreatedAt
  593. }
  594. if incoming.UpdatedAt > existing.UpdatedAt {
  595. existing.UpdatedAt = incoming.UpdatedAt
  596. }
  597. return conflicts
  598. }