model.go 22 KB

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