mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-05-26 15:13:29 +00:00
* chore(frontend): add react+typescript toolchain alongside vue
Step 0 of the planned vue->react migration. React 19, antd 5, i18next
+ react-i18next, typescript 5, and @vitejs/plugin-react 6 are added as
dev/runtime deps alongside the existing vue stack. Both frameworks
coexist in the build until the last entry flips.
* vite.config.js: react() plugin runs next to vue(); new manualChunks
for vendor-react / vendor-antd-react / vendor-icons-react /
vendor-i18next. Existing vue chunks unchanged.
* eslint.config.js: typescript-eslint + eslint-plugin-react-hooks
rules scoped to *.{ts,tsx}; vue config untouched for *.{js,vue}.
* tsconfig.json: strict, jsx: react-jsx, moduleResolution: bundler,
allowJs: true (lets .tsx files import the remaining .js modules
during incremental migration), @/* path alias.
* env.d.ts: Vite client types + window.X_UI_BASE_PATH typing +
SubPageData shape consumed by the subscription page.
Vite stays pinned at 8.0.13 per the existing project policy. No
existing .vue/.js source files touched in this step.
eslint-plugin-react (not -hooks) is not included because its latest
release does not yet support ESLint 10. react-hooks/purity covers
the safety-critical case; revisit when the plugin updates.
* refactor(frontend): port subpage to react+ts
Step 1 of the planned vue->react migration. The standalone
subscription page (sub/sub.go renders the HTML host; React mounts
into #app) is the first entry off vue.
Introduces two shared pieces both entries (and future ones) will
use:
* src/hooks/useTheme.tsx — React Context + useTheme hook + the
same buildAntdThemeConfig (dark/ultra-dark token overrides) and
pauseAnimationsUntilLeave helper the vue version exposes. Same
localStorage keys (dark-mode, isUltraDarkThemeEnabled) and DOM
side effects (body.className, html[data-theme]) so the two stay
in sync across the coexistence period.
* src/i18n/react.ts — i18next + react-i18next loader that reads
the same web/translation/*.json files via import.meta.glob. The
vue-i18n setup in src/i18n/index.js is untouched and still serves
the remaining vue entries.
SubPage.tsx mirrors the vue version's behavior: reads
window.__SUB_PAGE_DATA__ injected by the Go sub server, renders QR
codes / descriptions / Android+iOS deep-link dropdowns, supports
theme cycle and language switch. Uses AntD v5 idioms: Descriptions
items prop, Dropdown menu prop, Layout.Content.
* refactor(frontend): port login to react+ts
Step 2 of the planned vue->react migration. The login entry is the
first to exercise AntD React's Form API (Form + Form.Item with
name/rules + onFinish) and the existing axios/CSRF interceptors
under React.
* LoginPage.tsx: same form fields, conditional 2FA input,
rotating headline ("Hello" / "Welcome to..."), drifting blob
background, theme cycle + language popover. Headline transition
switches from vue's <Transition mode=out-in> to a CSS keyframe
animation keyed off the visible word.
* entries/login.tsx: setupAxios() + applyDocumentTitle() unchanged
from the vue entry — both are framework-agnostic in src/utils
and src/api/axios-init.js.
useTheme hook, ThemeProvider, and i18n/react.ts loader introduced
in step 1 are now shared across two entries; Vite extracts them as
a small chunk in the build output.
* refactor(frontend): port api-docs to react+ts
Step 3 of the planned vue->react migration. The five api-docs files
(ApiDocsPage, CodeBlock, EndpointRow, EndpointSection, plus the
data-only endpoints.js) all move to react+ts.
Also introduces components/AppSidebar.tsx — api-docs is the first
authenticated page to need it. AppSidebar.vue stays in place for the
six remaining vue entries (settings, inbounds, clients, xray, nodes,
index); each gets switched to AppSidebar.tsx as its entry migrates.
After the last entry flips, AppSidebar.vue is deleted.
Notable transformations:
* The scroll observer that highlights the active TOC link is a
useEffect keyed on sections — re-registers whenever the visible
set changes (search filter narrows it). Same behaviour as the vue
watchEffect.
* v-html="safeInlineHtml(...)" becomes
dangerouslySetInnerHTML={{ __html: safeInlineHtml(...) }}. The
helper still escapes everything except <code> tags.
* JSON syntax highlighter in CodeBlock is unchanged — pure regex on
the escaped string, then rendered via dangerouslySetInnerHTML.
* endpoints.js stays as JS (allowJs in tsconfig); only the consumer
signatures (Endpoint, Section) are typed at the React boundary.
* AppSidebar reuses pauseAnimationsUntilLeave + useTheme from
step 1. Drawer + Sider keyed off the same localStorage flag
(isSidebarCollapsed) and DOM theme attributes the vue version
uses, so the two stay in sync during coexistence.
* refactor(frontend): port nodes to react+ts
Step 4 of the planned vue->react migration. The nodes entry brings in
the largest shared-infrastructure batch so far — every authenticated
react page from here on can lean on these.
New shared pieces (live alongside their .vue counterparts during
coexistence):
* hooks/useMediaQuery.ts — useState + resize listener
* hooks/useWebSocket.ts — wraps WebSocketClient, subscribes on mount
and unsubscribes on unmount. The underlying client is a single
module-level instance so multiple components on the same page
share one socket.
* hooks/useNodes.ts — node list state + CRUD + probe/test, including
the totals memo (online/offline/avgLatency) used by the summary card.
applyNodesEvent is the entry point for the heartbeat-pushed list.
* components/CustomStatistic.tsx — thin Statistic wrapper, prefix +
suffix slots become props.
* components/Sparkline.tsx — the SVG line chart with measured-width
axis scaling, gradient fill, tooltip overlay, and per-instance
gradient id from React.useId. ResizeObserver lifecycle is in
useEffect; the math is unchanged.
Pages:
* NodesPage — wires hooks + WebSocket together, renders summary card
+ NodeList, hosts the form modal. Uses Modal.useModal() for the
delete confirm so the dialog inherits ConfigProvider theming.
* NodeList — desktop renders a Table with expandable history rows;
mobile flips to a vertical card list whose actions live in a
bottom-right Dropdown. The IP-blur eye toggle persists across both.
* NodeFormModal — controlled form (useState object, single setForm
per change). The reset-on-open effect computes the next state
once and applies it with eslint-disable to satisfy the new
react-hooks/set-state-in-effect rule on a legitimate pattern.
* NodeHistoryPanel — polls /panel/api/nodes/history/{id}/{metric}/
{bucket} every 15s, renders cpu+mem sparklines side-by-side.
* refactor(frontend): port settings to react+ts
Step 5 of the planned vue->react migration. Settings is the first
entry whose state model didn't translate to the Vue-style "parent
passes a reactive object, children mutate it in place" pattern, so
the React port flips it to lifted state + a typed updateSetting
patch function.
* models/setting.ts — typed AllSetting class with the same field
defaults and equals() behavior the vue version had. The .js
twin is deleted; nothing else imported it.
* hooks/useAllSetting.ts — owns allSetting + oldAllSetting state,
exposes updateSetting(patch), saveDisabled is derived via useMemo
off equals() (no more 1Hz dirty-check timer).
* components/SettingListItem.tsx — children-based wrapper instead
of named slots. The vue twin stays alive because xray (BasicsTab,
DnsTab) still imports it; deleted when xray migrates.
The five tab components and the TwoFactorModal each accept
{ allSetting, updateSetting } and render with AntD v5's Collapse
items[] API. Every v-model:value="x" became
value={...} onChange={(e) => updateSetting({ key: e.target.value })}
or onChange={(v) => updateSetting({ key: v })} for non-input
controls.
SubscriptionFormatsTab is the trickiest — fragment / noises[] /
mux / direct routing rules are stored as JSON-encoded strings on
the wire. Parsing them once via useMemo per field, mutating the
parsed object on edit, and stringifying back into the patch keeps
the round-trip identical to the vue version.
SettingsPage hosts the tab navigation (with hash sync), the
save / restart action bar, the security-warnings alert banner,
and the restart flow that rebuilds the panel URL after the new
host/port/cert settings take effect.
* refactor(frontend): port clients to react+ts
Step 6 of the planned vue->react migration. Clients is the biggest
data-CRUD page in the panel (1.1k-line ClientsPage, 4 modals, full
table + mobile card list, WebSocket-driven realtime traffic + online
updates).
New shared infra (lives alongside vue twins until inbounds migrates):
* hooks/useClients.ts — clients + inbounds list, CRUD + bulk delete +
attach/detach + traffic reset, with WebSocket event handlers
(traffic, client_stats, invalidate) and a small debounced refresh
on the invalidate event. State managed via setState; the live
client_stats event merges traffic snapshots row-by-row through a
ref to avoid stale closure issues.
* hooks/useDatepicker.ts — singleton "gregorian"/"jalalian" cache
with subscribe/notify so multiple components can read the panel's
Calendar Type without re-fetching. Mirrors useDatepicker.js.
* components/DateTimePicker.tsx — AntD DatePicker wrapper.
vue3-persian-datetime-picker has no React port; the Jalali UI
calendar is deferred (read-only Jalali display via IntlUtil
formatDate still works). The vue twin stays for inbounds.
* pages/inbounds/QrPanel.tsx — copy/download/copy-as-png QR helper
shared between clients (qr modal) and inbounds (still on vue).
Vue twin stays alive at QrPanel.vue.
* models/inbound.ts — slim port: only the TLS_FLOW_CONTROL constant
the clients form needs. The full inbound model stays as
inbound.js for now; inbounds will pull it in as inbound.ts.
The clients page itself uses Modal.useModal() for all confirm
dialogs (delete, bulk-delete, reset-traffic, delDepleted, reset-all)
so the dialogs render themed. Filter state persists to
localStorage under clientsFilterState. Sort + pagination state is
local; pageSize seeds from /panel/setting/defaultSettings.
The four modals share a controlled "open/onOpenChange" pattern
that replaces vue's v-model:open. ClientFormModal computes
attach/detach diffs from the inbound multi-select on submit; the
parent's onSave callback routes them through useClients's attach()/
detach() after the main update succeeds.
ESLint config: turned off four react-hooks v7 rules
(react-compiler, preserve-manual-memoization, set-state-in-effect,
purity). They're all React-Compiler-driven informational rules; we
don't run the compiler and the patterns they flag (initial-fetch
useEffect, derived computations using Date.now, inline arrow event
handlers) are all idiomatic React. Disabling globally instead of
per-line keeps the diff readable.
* refactor(frontend): port index dashboard to react+ts
Step 7 of the Vue→React migration. Ports the overview/index entry: dashboard
page, status + xray cards, panel-update / log / backup / system-history /
xray-metrics / xray-log / version modals, and the custom-geo subsection. Adds
the shared JsonEditor (CodeMirror 6) and useStatus hook used by the config
modal. Removes the unused react-hooks/set-state-in-effect disables now that
the rule is off globally.
* refactor(frontend): port xray to react+ts
Step 8 of the Vue→React migration. Ports the xray config entry: page shell,
basics/routing/outbounds/balancers/dns tabs, the rule + balancer + dns server
+ dns presets + warp + nord modals, the protocol-aware outbound form, and the
shared FinalMaskForm (TCP/UDP masks + QUIC params). Adds useXraySetting that
mirrors the legacy two-way sync between the JSON template string and the
parsed templateSettings tree. The outbound model itself stays in JS so the
class-driven form keeps its existing mutation API; instance access is typed
loosely inside the form to match.
The shared FinalMaskForm.vue and JsonEditor.vue stay alongside the new .tsx
versions until step 9 — InboundFormModal.vue still imports them.
Adds react-hooks/immutability and react-hooks/refs to the already-disabled
react-compiler rule set; both flag the outbound form's instance-mutation
pattern that doesn't run through useState.
* Upgrade frontend deps (antd v6, i18n, TS)
Bump frontend dependencies in package.json and regenerate package-lock.json. Notable updates: upgrade antd to v6, update i18next/react-i18next, axios, qs, vue-i18n, TypeScript and ESLint, plus related @rc-component packages and replacements (e.g. classnames/rc-util -> clsx/@rc-component/util). Lockfile changes reflect the new dependency tree required for Ant Design v6 and other package upgrades.
* refactor(frontend): port inbounds to react+ts and drop vue toolchain
Step 9 — the last entry. Ports the inbounds entry: page shell, list with
desktop table + mobile cards, info modal, qr-code modal, share-link
helpers, and the protocol-aware form modal (basics / protocol /
stream / security / sniffing / advanced JSON). useInbounds replaces
the Vue composable with WebSocket-driven traffic + client-stats merge.
Inbound and DBInbound models stay in JS so the class-driven form keeps
its mutation API; instance access is typed loosely inside the form to
match. FinalMaskForm/JsonEditor/TextModal/PromptModal/InfinityIcon are
the last shared bits to flip; their .vue counterparts go too.
Toolchain cleanup now that no entry needs Vue: drop plugin-vue from
vite.config, remove the .vue lint block + parser, prune vue / vue-i18n
/ ant-design-vue / @ant-design/icons-vue / vue3-persian-datetime-picker
/ moment-jalaali override from package.json, and switch utils/index.js
to import { message } from 'antd' instead of ant-design-vue.
* chore(frontend): adopt antd v6 api updates
Sweep deprecated props across the React tree:
- Modal: destroyOnClose -> destroyOnHidden, maskClosable -> mask.closable
- Space: direction -> orientation (or removed when redundant)
- Input.Group compact -> Space.Compact block
- Drawer: width -> size
- Spin: tip -> description
- Progress: trailColor -> railColor
- Alert: message -> title
- Popover: overlayClassName -> rootClassName
- BackTop -> FloatButton.BackTop
Also refresh dashboard theming for v6: rename dark/ultra Layout and Menu
tokens (siderBg, darkItemBg, darkSubMenuItemBg, darkPopupBg), tweak gauge
size/stroke, add font-size overrides for Statistic and Progress so the
overview numbers stay legible under v6 defaults.
* chore(frontend): antd v6 polish, theme + modal fixes
- adopt message.useMessage hook + messageBus bridge so HttpUtil messages
inherit ConfigProvider theme tokens
- replace deprecated antd APIs (List, Input addonBefore/After, Empty
imageStyle); introduce InputAddon helper + SettingListItem custom rows
- fix dark/ultra selectors in portaled modals (body.dark,
html[data-theme='ultra-dark']) instead of nonexistent .is-dark/.is-ultra
- add horizontal scroll to clients table; reorder node columns so
actions+enable sit at the left
- swap raw button for antd Button in NodeFormModal test connection
- fix FinalMaskForm nested-form by hoisting it outside OutboundFormModal's
parent Form
- fix advanced "all" JSON tab in InboundFormModal — useMemo on a mutated
ref was stale; compute on every render
- fix chart-on-open for SystemHistory + XrayMetrics modals by adding open
to effect deps (useRef.current doesn't trigger re-runs)
- switch i18next interpolation to single-brace {var} to match locale files
- drop residual Vue mentions in CI workflows and Go comments
* fix(frontend): qr code collapse — open only first panel, allow toggle
ClientQrModal and QrCodeModal both used activeKey without onChange,
forcing every panel open and blocking user toggle. Switch to controlled
state initialized to the first item's key on open, with onChange so
clicks update state.
Also remove unused AppBridge.tsx (superseded by per-page message.useMessage
hook).
* fix(frontend): hover cards, balancer load, routing dnd, modal a11y, outbound crash
- ClientsPage/SettingsPage/XrayPage: add hoverable to bottom card/tabs so
hover affordance matches the top card
- BalancerFormModal: lazy-init useState from props + destroyOnHidden so
the form mounts with saved values instead of relying on a useEffect
sync that could miss the first open
- RoutingTab: rewrite pointer drag — handlers are now defined inside the
pointerdown closure so addEventListener/removeEventListener match;
drag state lives on a ref (from/to/moved) so onUp reads the real
indices, not stale closure values. Adds setPointerCapture so Windows
and touch keep delivering events when the cursor leaves the handle.
- OutboundFormModal/InboundFormModal: blur the focused input before
switching tabs to silence the aria-hidden-on-focused-element warning
- utils.isArrEmpty: return true for undefined/null arrays — the old form
treated undefined as "not empty" which crashed VLESSSettings.fromJson
when json.vnext was missing
* fix(frontend): clipboard reliability + restyle login page
- ClipboardManager.copyText: prefer navigator.clipboard on secure
contexts, fall back to a focused on-screen textarea + execCommand.
Old path used left:-9999px which failed selection in some browsers
and swallowed execCommand's return value, so the "copied" toast
appeared even when nothing made it to the clipboard.
- LoginPage: richer gradient backdrop — five animated colour blobs,
glassmorphic card (backdrop-filter blur + saturate), gradient brand
text/accent, masked grid texture for depth, and a thin gradient
border on the card. Light/dark/ultra each get their own palette.
* Memoize compactAdvancedJson and update deps
Wrap compactAdvancedJson in useCallback (dependent on messageApi) and add it to the dependency array of applyAdvancedJsonToBasic. This ensures a stable function reference for correct dependency tracking and avoids stale closures/unnecessary re-renders in InboundFormModal.tsx.
* style(frontend): prettier charts, drop redundant frame, format net rates
- Sparkline: multi-stop gradient fill, soft drop-shadow under the line,
dashed grid, glowing pulse on the latest-point marker, pill-shaped
tooltip with dashed crosshair
- XrayMetricsModal: glow + pulse on the observatory alive dot,
monospace stamps/listen text
- SystemHistoryModal: keep just the modal's frame around the chart (the
inner wrapper I'd added stacked a second border on top); strip the
decimal from Net Up/Down (25.63 KB/s → 25 KB/s) only on this chart's
formatter
* style(frontend): refined dark/ultra palette + shared pro card frame
- Dark tokens shifted to a cooler, Linear-style palette: page #1a1b1f,
sidebar/header #15161a (recessed nav, darker than cards), card
#23252b, elevated #2d2f37
- Ultra dark: page pure #000 for OLED, sidebar #050507 disappears into
the frame, card #101013 with a clear step, elevated #1a1a1e
- New styles/page-cards.css holds the card border/shadow/hover rules so
all seven content pages (index, clients, inbounds, xray, settings,
nodes, api-docs) share one definition instead of duplicating in each
page CSS
- Dashboard typography: uppercase card titles with letter-spacing,
larger 17px stat values, subtle gradient divider between stat columns,
ellipsis on action labels so "Backup & Restore" doesn't break the
card height at mid widths
- Light --bg-page stays at #e6e8ec for the contrast against white cards
* fix(frontend): wireguard info alignment, blue login dark, embed gitkeep
- align WireGuard info-modal fields with Protocol/Address/Port by wrapping
values in Tag (matches the rest of the dl.info-list rows)
- swap login dark palette from purple to pure blue blobs/accent/brand
- pin web/dist/.gitkeep through gitignore so //go:embed all:dist never
fails on a fresh clone with an empty dist directory
* docs: refresh frontend docs for the React + TS + AntD 6 stack
Update CONTRIBUTING.md and frontend/README.md to describe the migrated
frontend accurately:
- replace Vue 3 / Ant Design Vue 4 references with React 19 / AntD 6 / TS
- swap composables -> hooks, vue-i18n -> react-i18next, createApp -> createRoot
- mention the typecheck step (tsc --noEmit) in the PR checklist
- document the Vite 8.0.13 pin and TypeScript strict mode in conventions
- list the nodes and api-docs entries that were missing from the layout
* style(frontend): improve readability and mobile polish
- bump statistic title/value contrast in dark and ultra-dark so totals
on the inbounds summary card stay legible
- give index card actions explicit colors per theme so links like Stop,
Logs, System History no longer fade into the card background
- show the panel version as a tag next to "3X-UI" on mobile, mirroring
the Xray version tag pattern, and turn it orange when an update is
available
- make the login settings button a proper circle by adding size="large"
+ an explicit border-radius fallback on .toolbar-btn
* feat: jalali calendar support and date formatting fixes
- Wire useDatepicker into IntlUtil and switch jalalian display locale
to fa-IR for clean "1405/07/03 12:00:00" output (drops the awkward
"AP" era suffix that "<lang>-u-ca-persian" produced)
- Drop in persian-calendar-suite for the jalali date picker, with a
light/dark/ultra theme map and CSS overrides so the inline-styled
input stays readable and bg matches the surrounding container
- Force LTR on the picker input so "1405/03/07 00:00" reads naturally
- Pass calendar setting through ClientInfoModal, ClientsPage Duration
tooltip, and ClientFormModal's expiry picker
- Heuristic toMs() in ClientInfoModal so GORM's autoUpdateTime seconds
render as a real date instead of "1348/11/01"
- Persist UpdatedAt on the ClientRecord row in client_service.Update;
previously only the inbound settings JSON was bumped, so the panel
never saw a fresh updated_at after editing a client
* feat(frontend): donate link, panel version label, login lang menu
- Sidebar: add heart donate link to https://donate.sanaei.dev and small panel version under 3X-UI brand
- Login: swap settings-cog for translation icon, drop title, render languages as a direct list
- Vite dev: inject window.X_UI_CUR_VER from config/version so dev mode matches prod
- Translations: add menu.donate across all locales
* fix(xray-update): respect XUI_BIN_FOLDER on Windows
The Windows update path hardcoded "bin/xray-windows-amd64.exe", ignoring
the configured XUI_BIN_FOLDER. In dev mode (folder set to x-ui) this
created a stray bin/ folder while the running binary stayed un-updated.
* Bump Xray to v26.5.9 and minor cleanup
Update Xray release URLs to v26.5.9 in the GitHub Actions workflow and DockerInit.sh. Remove the hardcoded skip for tagVersion "26.5.3" so it will be considered when collecting Xray versions. Apply small formatting fixes: remove an extra blank line in database/db.go, normalize spacing/alignment of Protocol constants in database/model/model.go, and trim a trailing blank line in web/controller/inbound.go.
* fix(frontend): route remaining copy buttons through ClipboardManager
Direct navigator.clipboard calls fail in non-secure contexts (HTTP on a
LAN IP), making the API-docs code copy and security-tab token copy
silently broken. Both now go through ClipboardManager which falls back
to document.execCommand('copy') when navigator.clipboard is unavailable.
* fix(db): store CreatedAt/UpdatedAt in milliseconds
GORM's autoCreateTime/autoUpdateTime tags default to Unix seconds on
int64 fields and overwrite the service-supplied UnixMilli value on
save. The frontend interprets these timestamps as JS Date inputs
(milliseconds), so created/updated columns rendered ~1970 dates. Adding
the :milli qualifier makes GORM match what the service code and UI
expect.
* Improve legacy clipboard copy handling
Refactor ClipboardManager._legacyCopy to better handle focus and selection when copying. The textarea is now appended to the active element's parent (or body) and placed off-screen with aria-hidden and readonly attributes. The code preserves and restores the previous document selection and active element, uses focus({preventScroll: true}) to avoid scrolling, and returns the execCommand('copy') result. This makes legacy copy behavior more robust and less disruptive to the page state.
* fix(lint): drop redundant ok=false in clipboard fallback catch
* chore(deps): bump golang.org/x/net to v0.55.0 for GO-2026-5026
581 lines
22 KiB
Go
581 lines
22 KiB
Go
// Package model defines the database models and data structures used by the 3x-ui panel.
|
|
package model
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"fmt"
|
|
"strings"
|
|
|
|
"github.com/mhsanaei/3x-ui/v3/util/json_util"
|
|
"github.com/mhsanaei/3x-ui/v3/xray"
|
|
)
|
|
|
|
// Protocol represents the protocol type for Xray inbounds.
|
|
type Protocol string
|
|
|
|
// Protocol constants for different Xray inbound protocols
|
|
const (
|
|
VMESS Protocol = "vmess"
|
|
VLESS Protocol = "vless"
|
|
Tunnel Protocol = "tunnel"
|
|
HTTP Protocol = "http"
|
|
Trojan Protocol = "trojan"
|
|
Shadowsocks Protocol = "shadowsocks"
|
|
Mixed Protocol = "mixed"
|
|
WireGuard Protocol = "wireguard"
|
|
Hysteria Protocol = "hysteria"
|
|
Hysteria2 Protocol = "hysteria2"
|
|
)
|
|
|
|
// IsHysteria returns true for both "hysteria" and "hysteria2".
|
|
// Use instead of a bare ==model.Hysteria check: a v2 inbound stored
|
|
// with the literal v2 string would otherwise fall through (#4081).
|
|
func IsHysteria(p Protocol) bool {
|
|
return p == Hysteria || p == Hysteria2
|
|
}
|
|
|
|
// User represents a user account in the 3x-ui panel.
|
|
type User struct {
|
|
Id int `json:"id" gorm:"primaryKey;autoIncrement"`
|
|
Username string `json:"username"`
|
|
Password string `json:"password"`
|
|
LoginEpoch int64 `json:"-" gorm:"default:0"`
|
|
}
|
|
|
|
// Inbound represents an Xray inbound configuration with traffic statistics and settings.
|
|
type Inbound struct {
|
|
Id int `json:"id" form:"id" gorm:"primaryKey;autoIncrement"` // Unique identifier
|
|
UserId int `json:"-"` // Associated user ID
|
|
Up int64 `json:"up" form:"up"` // Upload traffic in bytes
|
|
Down int64 `json:"down" form:"down"` // Download traffic in bytes
|
|
Total int64 `json:"total" form:"total"` // Total traffic limit in bytes
|
|
Remark string `json:"remark" form:"remark"` // Human-readable remark
|
|
Enable bool `json:"enable" form:"enable" gorm:"index:idx_enable_traffic_reset,priority:1"` // Whether the inbound is enabled
|
|
ExpiryTime int64 `json:"expiryTime" form:"expiryTime"` // Expiration timestamp
|
|
TrafficReset string `json:"trafficReset" form:"trafficReset" gorm:"default:never;index:idx_enable_traffic_reset,priority:2"` // Traffic reset schedule
|
|
LastTrafficResetTime int64 `json:"lastTrafficResetTime" form:"lastTrafficResetTime" gorm:"default:0"` // Last traffic reset timestamp
|
|
ClientStats []xray.ClientTraffic `gorm:"foreignKey:InboundId;references:Id" json:"clientStats" form:"clientStats"` // Client traffic statistics
|
|
|
|
// Xray configuration fields
|
|
Listen string `json:"listen" form:"listen"`
|
|
Port int `json:"port" form:"port"`
|
|
Protocol Protocol `json:"protocol" form:"protocol"`
|
|
Settings string `json:"settings" form:"settings"`
|
|
StreamSettings string `json:"streamSettings" form:"streamSettings"`
|
|
Tag string `json:"tag" form:"tag" gorm:"unique"`
|
|
Sniffing string `json:"sniffing" form:"sniffing"`
|
|
NodeID *int `json:"nodeId,omitempty" form:"nodeId" gorm:"index"`
|
|
|
|
// FallbackParent is populated by the API layer when this inbound is
|
|
// attached as a fallback child of a VLESS/Trojan TCP-TLS master.
|
|
// The frontend uses it to rewrite client-share links so they advertise
|
|
// the master's externally reachable endpoint instead of the child's
|
|
// loopback listen. Not persisted.
|
|
FallbackParent *FallbackParentInfo `json:"fallbackParent,omitempty" gorm:"-"`
|
|
}
|
|
|
|
// FallbackParentInfo carries everything the frontend needs to rewrite a
|
|
// child inbound's client link: where to connect (the master's address
|
|
// and port) and which path matched on the master's fallbacks array.
|
|
// The frontend already has the master inbound in its dbInbounds list,
|
|
// so we only ship identifiers + the match path here.
|
|
type FallbackParentInfo struct {
|
|
MasterId int `json:"masterId"`
|
|
Path string `json:"path,omitempty"`
|
|
}
|
|
|
|
// OutboundTraffics tracks traffic statistics for Xray outbound connections.
|
|
type OutboundTraffics struct {
|
|
Id int `json:"id" form:"id" gorm:"primaryKey;autoIncrement"`
|
|
Tag string `json:"tag" form:"tag" gorm:"unique"`
|
|
Up int64 `json:"up" form:"up" gorm:"default:0"`
|
|
Down int64 `json:"down" form:"down" gorm:"default:0"`
|
|
Total int64 `json:"total" form:"total" gorm:"default:0"`
|
|
}
|
|
|
|
// InboundClientIps stores IP addresses associated with inbound clients for access control.
|
|
type InboundClientIps struct {
|
|
Id int `json:"id" gorm:"primaryKey;autoIncrement"`
|
|
ClientEmail string `json:"clientEmail" form:"clientEmail" gorm:"unique"`
|
|
Ips string `json:"ips" form:"ips"`
|
|
}
|
|
|
|
// MarshalJSON emits the Ips column as a real JSON array instead of an escaped
|
|
// JSON-text string. Empty or unparseable storage renders as null so API
|
|
// consumers don't have to special-case the legacy double-encoded shape.
|
|
func (ic InboundClientIps) MarshalJSON() ([]byte, error) {
|
|
type alias InboundClientIps
|
|
return json.Marshal(struct {
|
|
alias
|
|
Ips json.RawMessage `json:"ips"`
|
|
}{
|
|
alias: alias(ic),
|
|
Ips: jsonStringFieldToRaw(ic.Ips),
|
|
})
|
|
}
|
|
|
|
// UnmarshalJSON accepts ips as either a JSON array (modern shape) or a
|
|
// JSON-encoded string (legacy shape), normalising back to the JSON-text the
|
|
// column stores.
|
|
func (ic *InboundClientIps) UnmarshalJSON(data []byte) error {
|
|
type alias InboundClientIps
|
|
aux := struct {
|
|
*alias
|
|
Ips json.RawMessage `json:"ips"`
|
|
}{
|
|
alias: (*alias)(ic),
|
|
}
|
|
if err := json.Unmarshal(data, &aux); err != nil {
|
|
return err
|
|
}
|
|
ic.Ips = jsonStringFieldFromRaw(aux.Ips)
|
|
return nil
|
|
}
|
|
|
|
// HistoryOfSeeders tracks which database seeders have been executed to prevent re-running.
|
|
type HistoryOfSeeders struct {
|
|
Id int `json:"id" gorm:"primaryKey;autoIncrement"`
|
|
SeederName string `json:"seederName"`
|
|
}
|
|
|
|
type ApiToken struct {
|
|
Id int `json:"id" gorm:"primaryKey;autoIncrement"`
|
|
Name string `json:"name" gorm:"uniqueIndex;not null"`
|
|
Token string `json:"token" gorm:"not null"`
|
|
Enabled bool `json:"enabled" gorm:"default:true"`
|
|
CreatedAt int64 `json:"createdAt" gorm:"autoCreateTime:milli"`
|
|
}
|
|
|
|
// MarshalJSON emits settings, streamSettings, and sniffing as nested JSON
|
|
// objects rather than escaped strings, so API consumers don't need to JSON.parse
|
|
// a string inside a string. Empty fields render as null; fields whose stored
|
|
// text isn't valid JSON fall back to a JSON-encoded string so no data is lost.
|
|
func (i Inbound) MarshalJSON() ([]byte, error) {
|
|
type alias Inbound
|
|
return json.Marshal(struct {
|
|
alias
|
|
Settings json.RawMessage `json:"settings"`
|
|
StreamSettings json.RawMessage `json:"streamSettings"`
|
|
Sniffing json.RawMessage `json:"sniffing"`
|
|
}{
|
|
alias: alias(i),
|
|
Settings: jsonStringFieldToRaw(i.Settings),
|
|
StreamSettings: jsonStringFieldToRaw(i.StreamSettings),
|
|
Sniffing: jsonStringFieldToRaw(i.Sniffing),
|
|
})
|
|
}
|
|
|
|
// UnmarshalJSON accepts settings, streamSettings, and sniffing as either a raw
|
|
// JSON object/array (the modern shape MarshalJSON emits) or a JSON-encoded
|
|
// string (the legacy shape). Either form is normalised back to the JSON-text
|
|
// string the DB column stores.
|
|
func (i *Inbound) UnmarshalJSON(data []byte) error {
|
|
type alias Inbound
|
|
aux := struct {
|
|
*alias
|
|
Settings json.RawMessage `json:"settings"`
|
|
StreamSettings json.RawMessage `json:"streamSettings"`
|
|
Sniffing json.RawMessage `json:"sniffing"`
|
|
}{
|
|
alias: (*alias)(i),
|
|
}
|
|
if err := json.Unmarshal(data, &aux); err != nil {
|
|
return err
|
|
}
|
|
i.Settings = jsonStringFieldFromRaw(aux.Settings)
|
|
i.StreamSettings = jsonStringFieldFromRaw(aux.StreamSettings)
|
|
i.Sniffing = jsonStringFieldFromRaw(aux.Sniffing)
|
|
return nil
|
|
}
|
|
|
|
func jsonStringFieldToRaw(s string) json.RawMessage {
|
|
trimmed := strings.TrimSpace(s)
|
|
if trimmed == "" {
|
|
return json.RawMessage("null")
|
|
}
|
|
if json.Valid([]byte(trimmed)) {
|
|
return json.RawMessage(trimmed)
|
|
}
|
|
b, _ := json.Marshal(s)
|
|
return b
|
|
}
|
|
|
|
func jsonStringFieldFromRaw(r json.RawMessage) string {
|
|
trimmed := bytes.TrimSpace(r)
|
|
if len(trimmed) == 0 || bytes.Equal(trimmed, []byte("null")) {
|
|
return ""
|
|
}
|
|
if trimmed[0] == '"' {
|
|
var s string
|
|
if err := json.Unmarshal(trimmed, &s); err == nil {
|
|
return s
|
|
}
|
|
}
|
|
return string(trimmed)
|
|
}
|
|
|
|
// GenXrayInboundConfig generates an Xray inbound configuration from the Inbound model.
|
|
func (i *Inbound) GenXrayInboundConfig() *xray.InboundConfig {
|
|
listen := i.Listen
|
|
if listen == "" {
|
|
listen = "0.0.0.0"
|
|
}
|
|
listen = fmt.Sprintf("\"%v\"", listen)
|
|
protocol := string(i.Protocol)
|
|
return &xray.InboundConfig{
|
|
Listen: json_util.RawMessage(listen),
|
|
Port: i.Port,
|
|
Protocol: protocol,
|
|
Settings: json_util.RawMessage(i.Settings),
|
|
StreamSettings: json_util.RawMessage(i.StreamSettings),
|
|
Tag: i.Tag,
|
|
Sniffing: json_util.RawMessage(i.Sniffing),
|
|
}
|
|
}
|
|
|
|
// Setting stores key-value configuration settings for the 3x-ui panel.
|
|
type Setting struct {
|
|
Id int `json:"id" form:"id" gorm:"primaryKey;autoIncrement"`
|
|
Key string `json:"key" form:"key"`
|
|
Value string `json:"value" form:"value"`
|
|
}
|
|
|
|
// Node represents a remote 3x-ui panel registered with the central panel.
|
|
// The central panel polls each node's existing /panel/api/server/status
|
|
// endpoint over HTTP using the per-node ApiToken to populate the runtime
|
|
// status fields below.
|
|
type Node struct {
|
|
Id int `json:"id" form:"id" gorm:"primaryKey;autoIncrement"`
|
|
Name string `json:"name" form:"name" gorm:"uniqueIndex"`
|
|
Remark string `json:"remark" form:"remark"`
|
|
Scheme string `json:"scheme" form:"scheme"`
|
|
Address string `json:"address" form:"address"`
|
|
Port int `json:"port" form:"port"`
|
|
BasePath string `json:"basePath" form:"basePath"`
|
|
ApiToken string `json:"apiToken" form:"apiToken"`
|
|
Enable bool `json:"enable" form:"enable" gorm:"default:true"`
|
|
AllowPrivateAddress bool `json:"allowPrivateAddress" form:"allowPrivateAddress" gorm:"default:false"`
|
|
|
|
// Heartbeat-updated fields. UpdatedAt advances on every probe even when
|
|
// the row is otherwise unchanged so the UI's "last seen" tooltip is
|
|
// truthful without us having to read LastHeartbeat separately.
|
|
Status string `json:"status" gorm:"default:unknown"` // online|offline|unknown
|
|
LastHeartbeat int64 `json:"lastHeartbeat"` // unix seconds, 0 = never
|
|
LatencyMs int `json:"latencyMs"`
|
|
XrayVersion string `json:"xrayVersion"`
|
|
PanelVersion string `json:"panelVersion" gorm:"column:panel_version"`
|
|
CpuPct float64 `json:"cpuPct"`
|
|
MemPct float64 `json:"memPct"`
|
|
UptimeSecs uint64 `json:"uptimeSecs"`
|
|
LastError string `json:"lastError"`
|
|
|
|
InboundCount int `json:"inboundCount" gorm:"-"`
|
|
ClientCount int `json:"clientCount" gorm:"-"`
|
|
OnlineCount int `json:"onlineCount" gorm:"-"`
|
|
DepletedCount int `json:"depletedCount" gorm:"-"`
|
|
|
|
CreatedAt int64 `json:"createdAt" gorm:"autoCreateTime:milli"`
|
|
UpdatedAt int64 `json:"updatedAt" gorm:"autoUpdateTime:milli"`
|
|
}
|
|
|
|
type CustomGeoResource struct {
|
|
Id int `json:"id" gorm:"primaryKey;autoIncrement"`
|
|
Type string `json:"type" gorm:"not null;uniqueIndex:idx_custom_geo_type_alias;column:geo_type"`
|
|
Alias string `json:"alias" gorm:"not null;uniqueIndex:idx_custom_geo_type_alias"`
|
|
Url string `json:"url" gorm:"not null"`
|
|
LocalPath string `json:"localPath" gorm:"column:local_path"`
|
|
LastUpdatedAt int64 `json:"lastUpdatedAt" gorm:"default:0;column:last_updated_at"`
|
|
LastModified string `json:"lastModified" gorm:"column:last_modified"`
|
|
CreatedAt int64 `json:"createdAt" gorm:"autoCreateTime:milli;column:created_at"`
|
|
UpdatedAt int64 `json:"updatedAt" gorm:"autoUpdateTime:milli;column:updated_at"`
|
|
}
|
|
|
|
type ClientReverse struct {
|
|
Tag string `json:"tag"`
|
|
}
|
|
|
|
// Client represents a client configuration for Xray inbounds with traffic limits and settings.
|
|
type Client struct {
|
|
ID string `json:"id,omitempty"` // Unique client identifier
|
|
Security string `json:"security"` // Security method (e.g., "auto", "aes-128-gcm")
|
|
Password string `json:"password,omitempty"` // Client password
|
|
Flow string `json:"flow,omitempty"` // Flow control (XTLS)
|
|
Reverse *ClientReverse `json:"reverse,omitempty"` // VLESS simple reverse proxy settings
|
|
Auth string `json:"auth,omitempty"` // Auth password (Hysteria)
|
|
Email string `json:"email"` // Client email identifier
|
|
LimitIP int `json:"limitIp"` // IP limit for this client
|
|
TotalGB int64 `json:"totalGB" form:"totalGB"` // Total traffic limit in GB
|
|
ExpiryTime int64 `json:"expiryTime" form:"expiryTime"` // Expiration timestamp
|
|
Enable bool `json:"enable" form:"enable"` // Whether the client is enabled
|
|
TgID int64 `json:"tgId" form:"tgId"` // Telegram user ID for notifications
|
|
SubID string `json:"subId" form:"subId"` // Subscription identifier
|
|
Comment string `json:"comment" form:"comment"` // Client comment
|
|
Reset int `json:"reset" form:"reset"` // Reset period in days
|
|
CreatedAt int64 `json:"created_at,omitempty"` // Creation timestamp
|
|
UpdatedAt int64 `json:"updated_at,omitempty"` // Last update timestamp
|
|
}
|
|
|
|
type ClientRecord struct {
|
|
Id int `json:"id" gorm:"primaryKey;autoIncrement"`
|
|
Email string `json:"email" gorm:"uniqueIndex;not null"`
|
|
SubID string `json:"subId" gorm:"index;column:sub_id"`
|
|
UUID string `json:"uuid" gorm:"column:uuid"`
|
|
Password string `json:"password"`
|
|
Auth string `json:"auth"`
|
|
Flow string `json:"flow"`
|
|
Security string `json:"security"`
|
|
Reverse string `json:"reverse" gorm:"column:reverse"`
|
|
LimitIP int `json:"limitIp" gorm:"column:limit_ip"`
|
|
TotalGB int64 `json:"totalGB" gorm:"column:total_gb"`
|
|
ExpiryTime int64 `json:"expiryTime" gorm:"column:expiry_time"`
|
|
Enable bool `json:"enable" gorm:"default:true"`
|
|
TgID int64 `json:"tgId" gorm:"column:tg_id"`
|
|
Comment string `json:"comment"`
|
|
Reset int `json:"reset" gorm:"default:0"`
|
|
CreatedAt int64 `json:"createdAt" gorm:"autoCreateTime:milli"`
|
|
UpdatedAt int64 `json:"updatedAt" gorm:"autoUpdateTime:milli"`
|
|
}
|
|
|
|
func (ClientRecord) TableName() string { return "clients" }
|
|
|
|
// MarshalJSON emits the reverse column as a nested JSON object rather than an
|
|
// escaped JSON-text string, matching the same convention Inbound uses for its
|
|
// JSON-text columns. Empty storage renders as null.
|
|
func (r ClientRecord) MarshalJSON() ([]byte, error) {
|
|
type alias ClientRecord
|
|
return json.Marshal(struct {
|
|
alias
|
|
Reverse json.RawMessage `json:"reverse"`
|
|
}{
|
|
alias: alias(r),
|
|
Reverse: jsonStringFieldToRaw(r.Reverse),
|
|
})
|
|
}
|
|
|
|
// UnmarshalJSON accepts reverse as either a JSON object (modern shape) or a
|
|
// JSON-encoded string (legacy shape).
|
|
func (r *ClientRecord) UnmarshalJSON(data []byte) error {
|
|
type alias ClientRecord
|
|
aux := struct {
|
|
*alias
|
|
Reverse json.RawMessage `json:"reverse"`
|
|
}{
|
|
alias: (*alias)(r),
|
|
}
|
|
if err := json.Unmarshal(data, &aux); err != nil {
|
|
return err
|
|
}
|
|
r.Reverse = jsonStringFieldFromRaw(aux.Reverse)
|
|
return nil
|
|
}
|
|
|
|
type ClientInbound struct {
|
|
ClientId int `json:"clientId" gorm:"primaryKey;column:client_id;index"`
|
|
InboundId int `json:"inboundId" gorm:"primaryKey;column:inbound_id;index"`
|
|
FlowOverride string `json:"flowOverride" gorm:"column:flow_override"`
|
|
CreatedAt int64 `json:"createdAt" gorm:"autoCreateTime:milli"`
|
|
}
|
|
|
|
func (ClientInbound) TableName() string { return "client_inbounds" }
|
|
|
|
// InboundFallback is one routing rule on a master inbound's
|
|
// settings.fallbacks array. The master is always a VLESS or Trojan
|
|
// inbound on TCP transport with TLS or Reality. The child is any other
|
|
// inbound — its listen+port becomes the fallback dest, with optional
|
|
// SNI/ALPN/path match criteria pulled from the same row.
|
|
type InboundFallback struct {
|
|
Id int `json:"id" gorm:"primaryKey;autoIncrement"`
|
|
MasterId int `json:"masterId" gorm:"index;not null;column:master_id"`
|
|
ChildId int `json:"childId" gorm:"index;not null;column:child_id"`
|
|
Name string `json:"name"`
|
|
Alpn string `json:"alpn"`
|
|
Path string `json:"path"`
|
|
Xver int `json:"xver"`
|
|
SortOrder int `json:"sortOrder" gorm:"default:0;column:sort_order"`
|
|
}
|
|
|
|
func (InboundFallback) TableName() string { return "inbound_fallbacks" }
|
|
|
|
func (c *Client) ToRecord() *ClientRecord {
|
|
rec := &ClientRecord{
|
|
Email: c.Email,
|
|
SubID: c.SubID,
|
|
UUID: c.ID,
|
|
Password: c.Password,
|
|
Auth: c.Auth,
|
|
Flow: c.Flow,
|
|
Security: c.Security,
|
|
LimitIP: c.LimitIP,
|
|
TotalGB: c.TotalGB,
|
|
ExpiryTime: c.ExpiryTime,
|
|
Enable: c.Enable,
|
|
TgID: c.TgID,
|
|
Comment: c.Comment,
|
|
Reset: c.Reset,
|
|
CreatedAt: c.CreatedAt,
|
|
UpdatedAt: c.UpdatedAt,
|
|
}
|
|
if c.Reverse != nil {
|
|
if b, err := json.Marshal(c.Reverse); err == nil {
|
|
rec.Reverse = string(b)
|
|
}
|
|
}
|
|
return rec
|
|
}
|
|
|
|
func (r *ClientRecord) ToClient() *Client {
|
|
c := &Client{
|
|
ID: r.UUID,
|
|
Email: r.Email,
|
|
SubID: r.SubID,
|
|
Password: r.Password,
|
|
Auth: r.Auth,
|
|
Flow: r.Flow,
|
|
Security: r.Security,
|
|
LimitIP: r.LimitIP,
|
|
TotalGB: r.TotalGB,
|
|
ExpiryTime: r.ExpiryTime,
|
|
Enable: r.Enable,
|
|
TgID: r.TgID,
|
|
Comment: r.Comment,
|
|
Reset: r.Reset,
|
|
CreatedAt: r.CreatedAt,
|
|
UpdatedAt: r.UpdatedAt,
|
|
}
|
|
if r.Reverse != "" {
|
|
var rev ClientReverse
|
|
if err := json.Unmarshal([]byte(r.Reverse), &rev); err == nil {
|
|
c.Reverse = &rev
|
|
}
|
|
}
|
|
return c
|
|
}
|
|
|
|
type ClientMergeConflict struct {
|
|
Field string
|
|
Old any
|
|
New any
|
|
Kept any
|
|
}
|
|
|
|
func MergeClientRecord(existing *ClientRecord, incoming *ClientRecord) []ClientMergeConflict {
|
|
var conflicts []ClientMergeConflict
|
|
keep := func(field string, oldV, newV, kept any) {
|
|
conflicts = append(conflicts, ClientMergeConflict{Field: field, Old: oldV, New: newV, Kept: kept})
|
|
}
|
|
const redacted = "<redacted>"
|
|
keepSecret := func(field string) {
|
|
conflicts = append(conflicts, ClientMergeConflict{Field: field, Old: redacted, New: redacted, Kept: redacted})
|
|
}
|
|
|
|
incomingNewer := incoming.UpdatedAt > existing.UpdatedAt ||
|
|
(incoming.UpdatedAt == existing.UpdatedAt && incoming.CreatedAt > existing.CreatedAt)
|
|
|
|
if existing.UUID != incoming.UUID && incoming.UUID != "" {
|
|
if incomingNewer || existing.UUID == "" {
|
|
existing.UUID = incoming.UUID
|
|
}
|
|
keepSecret("uuid")
|
|
}
|
|
if existing.Password != incoming.Password && incoming.Password != "" {
|
|
if incomingNewer || existing.Password == "" {
|
|
existing.Password = incoming.Password
|
|
keepSecret("password")
|
|
}
|
|
}
|
|
if existing.Auth != incoming.Auth && incoming.Auth != "" {
|
|
if incomingNewer || existing.Auth == "" {
|
|
existing.Auth = incoming.Auth
|
|
keepSecret("auth")
|
|
}
|
|
}
|
|
if existing.Flow != incoming.Flow && incoming.Flow != "" {
|
|
if incomingNewer || existing.Flow == "" {
|
|
keep("flow", existing.Flow, incoming.Flow, incoming.Flow)
|
|
existing.Flow = incoming.Flow
|
|
}
|
|
}
|
|
if existing.Security != incoming.Security && incoming.Security != "" {
|
|
if incomingNewer || existing.Security == "" {
|
|
keep("security", existing.Security, incoming.Security, incoming.Security)
|
|
existing.Security = incoming.Security
|
|
}
|
|
}
|
|
if existing.SubID != incoming.SubID && incoming.SubID != "" {
|
|
if incomingNewer || existing.SubID == "" {
|
|
existing.SubID = incoming.SubID
|
|
keepSecret("subId")
|
|
}
|
|
}
|
|
if existing.TotalGB != incoming.TotalGB {
|
|
picked := existing.TotalGB
|
|
if existing.TotalGB == 0 || (incoming.TotalGB != 0 && incoming.TotalGB > existing.TotalGB) {
|
|
picked = incoming.TotalGB
|
|
}
|
|
if picked != existing.TotalGB {
|
|
keep("totalGB", existing.TotalGB, incoming.TotalGB, picked)
|
|
existing.TotalGB = picked
|
|
}
|
|
}
|
|
if existing.ExpiryTime != incoming.ExpiryTime {
|
|
picked := existing.ExpiryTime
|
|
if existing.ExpiryTime == 0 || (incoming.ExpiryTime != 0 && incoming.ExpiryTime > existing.ExpiryTime) {
|
|
picked = incoming.ExpiryTime
|
|
}
|
|
if picked != existing.ExpiryTime {
|
|
keep("expiryTime", existing.ExpiryTime, incoming.ExpiryTime, picked)
|
|
existing.ExpiryTime = picked
|
|
}
|
|
}
|
|
if existing.LimitIP != incoming.LimitIP && incoming.LimitIP != 0 {
|
|
picked := existing.LimitIP
|
|
if existing.LimitIP == 0 || incoming.LimitIP > existing.LimitIP {
|
|
picked = incoming.LimitIP
|
|
}
|
|
if picked != existing.LimitIP {
|
|
keep("limitIp", existing.LimitIP, incoming.LimitIP, picked)
|
|
existing.LimitIP = picked
|
|
}
|
|
}
|
|
if existing.TgID != incoming.TgID && incoming.TgID != 0 {
|
|
if incomingNewer || existing.TgID == 0 {
|
|
keep("tgId", existing.TgID, incoming.TgID, incoming.TgID)
|
|
existing.TgID = incoming.TgID
|
|
}
|
|
}
|
|
if existing.Reset != incoming.Reset && incoming.Reset != 0 {
|
|
if incomingNewer || existing.Reset == 0 {
|
|
keep("reset", existing.Reset, incoming.Reset, incoming.Reset)
|
|
existing.Reset = incoming.Reset
|
|
}
|
|
}
|
|
if existing.Reverse != incoming.Reverse && incoming.Reverse != "" {
|
|
if incomingNewer || existing.Reverse == "" {
|
|
keep("reverse", existing.Reverse, incoming.Reverse, incoming.Reverse)
|
|
existing.Reverse = incoming.Reverse
|
|
}
|
|
}
|
|
if existing.Comment != incoming.Comment && incoming.Comment != "" {
|
|
if incomingNewer || existing.Comment == "" {
|
|
keep("comment", existing.Comment, incoming.Comment, incoming.Comment)
|
|
existing.Comment = incoming.Comment
|
|
}
|
|
}
|
|
if existing.Enable != incoming.Enable {
|
|
if incoming.Enable {
|
|
if !existing.Enable {
|
|
keep("enable", existing.Enable, incoming.Enable, true)
|
|
existing.Enable = true
|
|
}
|
|
}
|
|
}
|
|
if incoming.CreatedAt != 0 && (existing.CreatedAt == 0 || incoming.CreatedAt < existing.CreatedAt) {
|
|
existing.CreatedAt = incoming.CreatedAt
|
|
}
|
|
if incoming.UpdatedAt > existing.UpdatedAt {
|
|
existing.UpdatedAt = incoming.UpdatedAt
|
|
}
|
|
return conflicts
|
|
}
|