mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-07-12 15:46:06 +00:00
Reduce list-page payloads with slim/paged endpoints (#4500)
* perf(inbounds): slim list payload + lazy hydrate for row actions
Adds GET /panel/api/inbounds/list/slim that returns the same list shape
but strips every per-client field besides email/enable/comment from
settings.clients[] and skips UUID/SubId enrichment on ClientStats.
The inbounds page only reads those three to compute its client counters
and badges, so the slim variant trims tens of bytes per client (uuid,
password, flow, security, totalGB, expiryTime, limitIp, tgId, ...).
On a panel with thousands of clients this is the dominant load-time
cost.
Detail flows (edit / info / qr / export / clone) call /get/:id through
a new hydrateInbound helper before opening — the slim list view never
needs the secrets it doesn't render.
* perf(clients): server-side pagination + slim row payload
Adds GET /panel/api/clients/list/paged that filters, sorts, and paginates
on the server, returns a slim row shape (drops uuid/password/auth/flow/
security/reverse/tgId per client), and includes a stable summary
(total, active, online[], depleted[], expiring[], deactive[]) computed
across the full DB row set so the dashboard cards don't change as the
user paginates or filters. Page size capped at 200.
useClients now exposes { clients (current page), total, filtered, query,
setQuery, summary, hydrate }. ClientsPage feeds its filter/sort/page
state into setQuery via a single effect, debounces search by 300ms, and
hydrates the full client record via /get/:email before opening edit/info/
qr modals. Local filter/sort logic and the all-clients summary memo are
gone.
On a 2000-client panel this turns the initial response from ~MB to ~25 row
slice (~10s of KB) and removes the all-client parse cost from every
refresh.
* perf(settings): use /inbounds/options for LDAP tag picker
The General settings tab only needs each inbound's tag/protocol/port to
fill a dropdown but was calling /panel/api/inbounds/list which ships the
full settings JSON with every embedded client. Switched it to /options
and added Tag to the projection. On a panel with thousands of clients
this drops the General-tab load payload from megabytes to a tiny
per-inbound row each.
* perf(clients): de-duplicate options + paged list fetches
Two issues caused each clients-page load to fire its requests twice:
1. setQuery in the hook took whatever object the consumer passed and
stored it as-is. The consumer (ClientsPage) constructs a new object
literal in an effect, so even when nothing actually changed the ref
was new — the hook's useEffect saw a new query and re-fetched.
Wrapped setQuery with a shallow value compare so identical params
are a no-op.
2. The picker /inbounds/options fetch was bundled into refresh() with a
length==0 guard, but the two back-to-back refreshes both saw an
empty inbounds array (the first hadn't resolved yet) so both fired
the request. Moved the options fetch into its own one-shot effect.
* perf(inbounds): share nodes list with form modal instead of refetching
InboundsPage and InboundFormModal both called useNodes() — each
instance maintains its own state and fires its own /panel/api/nodes/list
fetch on mount. Since the modal is always rendered (open or not), every
page load hit the endpoint twice.
Threaded nodes from the page through an availableNodes prop on the form
modal so they share one fetch.
* docs(api): register /clients/list/paged endpoint
TestAPIRoutesDocumented was failing because the new paginated clients
endpoint added in this branch wasn't listed in endpoints.js.
This commit is contained in:
@@ -54,12 +54,65 @@ interface SubSettings {
|
||||
subJsonEnable: boolean;
|
||||
}
|
||||
|
||||
export interface ClientQueryParams {
|
||||
page: number;
|
||||
pageSize: number;
|
||||
search?: string;
|
||||
filter?: string;
|
||||
protocol?: string;
|
||||
sort?: string;
|
||||
order?: 'ascend' | 'descend';
|
||||
}
|
||||
|
||||
export interface ClientsSummary {
|
||||
total: number;
|
||||
active: number;
|
||||
online: string[];
|
||||
depleted: string[];
|
||||
expiring: string[];
|
||||
deactive: string[];
|
||||
}
|
||||
|
||||
interface ClientPageResponse {
|
||||
items: ClientRecord[];
|
||||
total: number;
|
||||
filtered: number;
|
||||
page: number;
|
||||
pageSize: number;
|
||||
summary?: ClientsSummary;
|
||||
}
|
||||
|
||||
const DEFAULT_QUERY: ClientQueryParams = { page: 1, pageSize: 25 };
|
||||
|
||||
export function useClients() {
|
||||
const [clients, setClients] = useState<ClientRecord[]>([]);
|
||||
const [total, setTotal] = useState(0);
|
||||
const [filtered, setFiltered] = useState(0);
|
||||
const [summary, setSummary] = useState<ClientsSummary>({
|
||||
total: 0, active: 0, online: [], depleted: [], expiring: [], deactive: [],
|
||||
});
|
||||
const [inbounds, setInbounds] = useState<InboundOption[]>([]);
|
||||
const [onlines, setOnlines] = useState<string[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [fetched, setFetched] = useState(false);
|
||||
const [query, setQueryState] = useState<ClientQueryParams>(DEFAULT_QUERY);
|
||||
// Shallow-compare against the previous query so callers can pass a fresh
|
||||
// object on every render (the common React pattern) without triggering a
|
||||
// re-fetch when nothing actually changed.
|
||||
const setQuery = useCallback((next: ClientQueryParams) => {
|
||||
setQueryState((prev) => {
|
||||
if (
|
||||
prev.page === next.page
|
||||
&& prev.pageSize === next.pageSize
|
||||
&& (prev.search ?? '') === (next.search ?? '')
|
||||
&& (prev.filter ?? '') === (next.filter ?? '')
|
||||
&& (prev.protocol ?? '') === (next.protocol ?? '')
|
||||
&& (prev.sort ?? '') === (next.sort ?? '')
|
||||
&& (prev.order ?? '') === (next.order ?? '')
|
||||
) return prev;
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
const [subSettings, setSubSettings] = useState<SubSettings>({
|
||||
enable: false, subURI: '', subJsonURI: '', subJsonEnable: false,
|
||||
});
|
||||
@@ -70,22 +123,35 @@ export function useClients() {
|
||||
const [pageSize, setPageSize] = useState(0);
|
||||
|
||||
const clientsRef = useRef<ClientRecord[]>([]);
|
||||
const queryRef = useRef<ClientQueryParams>(query);
|
||||
const invalidateTimerRef = useRef<number | null>(null);
|
||||
|
||||
useEffect(() => { clientsRef.current = clients; }, [clients]);
|
||||
useEffect(() => { queryRef.current = query; }, [query]);
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
const buildQS = (p: ClientQueryParams) => {
|
||||
const sp = new URLSearchParams();
|
||||
sp.set('page', String(p.page || 1));
|
||||
sp.set('pageSize', String(p.pageSize || DEFAULT_QUERY.pageSize));
|
||||
if (p.search) sp.set('search', p.search);
|
||||
if (p.filter) sp.set('filter', p.filter);
|
||||
if (p.protocol) sp.set('protocol', p.protocol);
|
||||
if (p.sort) sp.set('sort', p.sort);
|
||||
if (p.order) sp.set('order', p.order);
|
||||
return sp.toString();
|
||||
};
|
||||
|
||||
const refresh = useCallback(async (override?: ClientQueryParams) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const [clientsMsg, inboundsMsg] = await Promise.all([
|
||||
HttpUtil.get('/panel/api/clients/list') as Promise<ApiMsg<ClientRecord[]>>,
|
||||
HttpUtil.get('/panel/api/inbounds/options') as Promise<ApiMsg<InboundOption[]>>,
|
||||
]);
|
||||
if (clientsMsg?.success) {
|
||||
setClients(Array.isArray(clientsMsg.obj) ? clientsMsg.obj : []);
|
||||
}
|
||||
if (inboundsMsg?.success) {
|
||||
setInbounds(Array.isArray(inboundsMsg.obj) ? inboundsMsg.obj : []);
|
||||
const params = override ?? queryRef.current;
|
||||
const qs = buildQS(params);
|
||||
const msg = await HttpUtil.get(`/panel/api/clients/list/paged?${qs}`) as ApiMsg<ClientPageResponse>;
|
||||
if (msg?.success && msg.obj) {
|
||||
setClients(Array.isArray(msg.obj.items) ? msg.obj.items : []);
|
||||
setTotal(msg.obj.total ?? 0);
|
||||
setFiltered(msg.obj.filtered ?? 0);
|
||||
if (msg.obj.summary) setSummary(msg.obj.summary);
|
||||
}
|
||||
setFetched(true);
|
||||
} finally {
|
||||
@@ -93,6 +159,18 @@ export function useClients() {
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Inbound options are picker-shaped and don't depend on the clients query —
|
||||
// fetch them once on mount instead of every refresh.
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
(async () => {
|
||||
const msg = await HttpUtil.get('/panel/api/inbounds/options') as ApiMsg<InboundOption[]>;
|
||||
if (cancelled) return;
|
||||
if (msg?.success) setInbounds(Array.isArray(msg.obj) ? msg.obj : []);
|
||||
})();
|
||||
return () => { cancelled = true; };
|
||||
}, []);
|
||||
|
||||
const fetchSubSettings = useCallback(async () => {
|
||||
const msg = await HttpUtil.post('/panel/setting/defaultSettings') as ApiMsg<Record<string, unknown>>;
|
||||
if (!msg?.success) return;
|
||||
@@ -110,6 +188,17 @@ export function useClients() {
|
||||
setPageSize((s.pageSize as number) ?? 0);
|
||||
}, []);
|
||||
|
||||
// hydrate fetches the full client record (uuid, password, flow, ...) for a
|
||||
// single email. The paged list endpoint omits these to keep the row payload
|
||||
// tiny; edit / info / qr / link modals call this to get a complete record
|
||||
// before opening.
|
||||
const hydrate = useCallback(async (email: string): Promise<{ client: ClientRecord; inboundIds: number[] } | null> => {
|
||||
if (!email) return null;
|
||||
const msg = await HttpUtil.get(`/panel/api/clients/get/${encodeURIComponent(email)}`) as ApiMsg<{ client: ClientRecord; inboundIds: number[] }>;
|
||||
if (!msg?.success || !msg.obj) return null;
|
||||
return msg.obj;
|
||||
}, []);
|
||||
|
||||
const create = useCallback(async (payload: unknown) => {
|
||||
const msg = await HttpUtil.post('/panel/api/clients/add', payload, JSON_HEADERS) as ApiMsg;
|
||||
if (msg?.success) await refresh();
|
||||
@@ -258,13 +347,18 @@ export function useClients() {
|
||||
}, [refresh]);
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
Promise.all([refresh(), fetchSubSettings()]);
|
||||
|
||||
}, [refresh, fetchSubSettings]);
|
||||
Promise.all([refresh(query), fetchSubSettings()]);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [query, fetchSubSettings]);
|
||||
|
||||
return {
|
||||
clients,
|
||||
total,
|
||||
filtered,
|
||||
summary,
|
||||
hydrate,
|
||||
query,
|
||||
setQuery,
|
||||
inbounds,
|
||||
onlines,
|
||||
loading,
|
||||
|
||||
@@ -80,6 +80,13 @@ export const sections = [
|
||||
response:
|
||||
'{\n "success": true,\n "obj": [\n {\n "id": 1,\n "userId": 1,\n "up": 0,\n "down": 0,\n "total": 0,\n "remark": "VLESS-443",\n "enable": true,\n "expiryTime": 0,\n "listen": "",\n "port": 443,\n "protocol": "vless",\n "settings": {\n "clients": [],\n "decryption": "none"\n },\n "streamSettings": {\n "network": "tcp",\n "security": "reality",\n "realitySettings": { "show": false, "dest": "..." }\n },\n "tag": "inbound-443",\n "sniffing": {\n "enabled": true,\n "destOverride": ["http", "tls"]\n },\n "clientStats": []\n }\n ]\n}',
|
||||
},
|
||||
{
|
||||
method: 'GET',
|
||||
path: '/panel/api/inbounds/list/slim',
|
||||
summary: 'Same shape as /list but with settings.clients[] stripped down to {email, enable, comment} and ClientStats not enriched with UUID/SubId. Use this for list pages; fetch /get/:id when you need the full per-client payload (uuid, password, flow, ...).',
|
||||
response:
|
||||
'{\n "success": true,\n "obj": [\n {\n "id": 1,\n "userId": 1,\n "remark": "VLESS-443",\n "settings": {\n "clients": [\n { "email": "alice", "enable": true }\n ],\n "decryption": "none"\n },\n "clientStats": []\n }\n ]\n}',
|
||||
},
|
||||
{
|
||||
method: 'GET',
|
||||
path: '/panel/api/inbounds/options',
|
||||
@@ -386,6 +393,22 @@ export const sections = [
|
||||
response:
|
||||
'{\n "success": true,\n "obj": [\n {\n "id": 1,\n "email": "alice@example.com",\n "subId": "abcd1234",\n "uuid": "...",\n "totalGB": 53687091200,\n "expiryTime": 1735689600000,\n "enable": true,\n "reverse": null,\n "inboundIds": [3, 5],\n "traffic": { "up": 1024, "down": 4096, "enable": true }\n }\n ]\n}',
|
||||
},
|
||||
{
|
||||
method: 'GET',
|
||||
path: '/panel/api/clients/list/paged',
|
||||
summary: 'Filter, sort, and paginate clients on the server. Each item is a slim row (no uuid/password/auth/flow/security/reverse/tgId) so the clients page can ship 25-ish rows in a few KB instead of the full table. The response also includes a summary computed across the full DB row set so dashboard counters stay stable as the user paginates or filters. Page size capped at 200; fetch /get/:email to obtain the full per-client payload for an edit/info modal.',
|
||||
params: [
|
||||
{ name: 'page', in: 'query', type: 'number', desc: '1-indexed page number. Defaults to 1.' },
|
||||
{ name: 'pageSize', in: 'query', type: 'number', desc: 'Rows per page. Defaults to 25, capped at 200.' },
|
||||
{ name: 'search', in: 'query', type: 'string', desc: 'Case-insensitive substring match on email / subId / comment.' },
|
||||
{ name: 'filter', in: 'query', type: 'string', desc: 'Status bucket: online | active | deactive | depleted | expiring.' },
|
||||
{ name: 'protocol', in: 'query', type: 'string', desc: 'Match clients attached to at least one inbound of this protocol (vless, vmess, trojan, shadowsocks, ...).' },
|
||||
{ name: 'sort', in: 'query', type: 'string', desc: 'Sort key: enable | email | inboundIds | traffic | remaining | expiryTime.' },
|
||||
{ name: 'order', in: 'query', type: 'string', desc: 'ascend or descend.' },
|
||||
],
|
||||
response:
|
||||
'{\n "success": true,\n "obj": {\n "items": [\n {\n "email": "alice@example.com",\n "subId": "abcd1234",\n "enable": true,\n "totalGB": 53687091200,\n "expiryTime": 1735689600000,\n "limitIp": 0,\n "reset": 0,\n "inboundIds": [3, 5],\n "traffic": { "up": 1024, "down": 4096, "enable": true },\n "createdAt": 1735000000000,\n "updatedAt": 1735100000000\n }\n ],\n "total": 2000,\n "filtered": 47,\n "page": 1,\n "pageSize": 25,\n "summary": {\n "total": 2000,\n "active": 1850,\n "online": ["alice@example.com"],\n "depleted": [],\n "expiring": [],\n "deactive": []\n }\n }\n}',
|
||||
},
|
||||
{
|
||||
method: 'GET',
|
||||
path: '/panel/api/clients/get/:email',
|
||||
|
||||
@@ -49,7 +49,7 @@ import { useDatepicker } from '@/hooks/useDatepicker';
|
||||
import type { ClientRecord, InboundOption } from '@/hooks/useClients';
|
||||
import AppSidebar from '@/components/AppSidebar';
|
||||
import CustomStatistic from '@/components/CustomStatistic';
|
||||
import { IntlUtil, ObjectUtil, SizeFormatter } from '@/utils';
|
||||
import { IntlUtil, SizeFormatter } from '@/utils';
|
||||
import { setMessageInstance } from '@/utils/messageBus';
|
||||
import ClientFormModal from './ClientFormModal';
|
||||
import ClientInfoModal from './ClientInfoModal';
|
||||
@@ -96,11 +96,15 @@ export default function ClientsPage() {
|
||||
useEffect(() => { setMessageInstance(messageApi); }, [messageApi]);
|
||||
|
||||
const {
|
||||
clients, inbounds, onlines, loading, fetched, subSettings,
|
||||
clients, filtered,
|
||||
summary: serverSummary,
|
||||
setQuery,
|
||||
inbounds, onlines, loading, fetched, subSettings,
|
||||
ipLimitEnable, tgBotEnable, expireDiff, trafficDiff, pageSize,
|
||||
create, update, remove, removeMany, bulkAdjust, attach, detach,
|
||||
resetTraffic, resetAllTraffics, delDepleted, setEnable,
|
||||
applyTrafficEvent, applyClientStatsEvent, applyInvalidate,
|
||||
hydrate,
|
||||
} = useClients();
|
||||
|
||||
useWebSocket({
|
||||
@@ -131,7 +135,10 @@ export default function ClientsPage() {
|
||||
const [sortColumn, setSortColumn] = useState<string | null>(null);
|
||||
const [sortOrder, setSortOrder] = useState<'ascend' | 'descend' | null>(null);
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
const [tablePageSize, setTablePageSize] = useState(20);
|
||||
const [tablePageSize, setTablePageSize] = useState(25);
|
||||
// debouncedSearch lags behind the input so we don't spam the server on every
|
||||
// keystroke; the search box still feels instant locally.
|
||||
const [debouncedSearch, setDebouncedSearch] = useState(searchKey);
|
||||
|
||||
useEffect(() => {
|
||||
localStorage.setItem(FILTER_STATE_KEY, JSON.stringify({
|
||||
@@ -139,6 +146,29 @@ export default function ClientsPage() {
|
||||
}));
|
||||
}, [enableFilter, searchKey, filterBy, protocolFilter]);
|
||||
|
||||
useEffect(() => {
|
||||
const handle = window.setTimeout(() => setDebouncedSearch(searchKey), 300);
|
||||
return () => window.clearTimeout(handle);
|
||||
}, [searchKey]);
|
||||
|
||||
useEffect(() => {
|
||||
// Reset to page 1 whenever a filter or sort changes — otherwise an empty
|
||||
// result set on a high page number leaves the user staring at "no clients".
|
||||
setCurrentPage(1);
|
||||
}, [debouncedSearch, enableFilter, filterBy, protocolFilter, sortColumn, sortOrder]);
|
||||
|
||||
useEffect(() => {
|
||||
setQuery({
|
||||
page: currentPage,
|
||||
pageSize: tablePageSize,
|
||||
search: enableFilter ? '' : debouncedSearch,
|
||||
filter: enableFilter ? (filterBy || '') : '',
|
||||
protocol: protocolFilter || '',
|
||||
sort: sortColumn || undefined,
|
||||
order: sortOrder || undefined,
|
||||
});
|
||||
}, [setQuery, currentPage, tablePageSize, enableFilter, debouncedSearch, filterBy, protocolFilter, sortColumn, sortOrder]);
|
||||
|
||||
useEffect(() => {
|
||||
if (pageSize > 0) {
|
||||
|
||||
@@ -192,81 +222,18 @@ export default function ClientsPage() {
|
||||
}
|
||||
}
|
||||
|
||||
function clientMatchesProtocol(row: ClientRecord, protocol?: string) {
|
||||
if (!protocol) return true;
|
||||
const ids = Array.isArray(row.inboundIds) ? row.inboundIds : [];
|
||||
for (const id of ids) {
|
||||
const ib = inboundsById[id];
|
||||
if (ib && ib.protocol === protocol) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
// The list page renders rows the server already sorted, filtered, and
|
||||
// paginated. Local filtering is gone — keep the variable name so the rest
|
||||
// of the file (table dataSource, mobile cards, select-all) doesn't need
|
||||
// a rename.
|
||||
const filteredClients = clients;
|
||||
|
||||
const filteredClients = useMemo(() => {
|
||||
let rows = clients || [];
|
||||
if (enableFilter) {
|
||||
if (filterBy === 'online') {
|
||||
rows = rows.filter((r) => r.enable && isOnline(r.email));
|
||||
} else if (filterBy) {
|
||||
rows = rows.filter((r) => clientBucket(r) === filterBy);
|
||||
}
|
||||
} else if (!ObjectUtil.isEmpty(searchKey)) {
|
||||
rows = rows.filter((r) => ObjectUtil.deepSearch(r, searchKey));
|
||||
}
|
||||
if (protocolFilter) {
|
||||
rows = rows.filter((r) => clientMatchesProtocol(r, protocolFilter));
|
||||
}
|
||||
return rows;
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [clients, enableFilter, filterBy, searchKey, protocolFilter, clientBucket]);
|
||||
// Server-computed counts that stay stable as the user paginates/filters.
|
||||
const summary = serverSummary;
|
||||
|
||||
const summary = useMemo(() => {
|
||||
const rows = clients || [];
|
||||
const deactive: string[] = [];
|
||||
const depleted: string[] = [];
|
||||
const expiring: string[] = [];
|
||||
const online: string[] = [];
|
||||
let active = 0;
|
||||
for (const row of rows) {
|
||||
const bucket = clientBucket(row);
|
||||
if (bucket === 'deactive') deactive.push(row.email);
|
||||
else if (bucket === 'depleted') depleted.push(row.email);
|
||||
else if (bucket === 'expiring') expiring.push(row.email);
|
||||
else if (bucket === 'active') active++;
|
||||
if (row.enable && isOnline(row.email)) online.push(row.email);
|
||||
}
|
||||
return { total: rows.length, active, deactive, depleted, expiring, online };
|
||||
}, [clients, clientBucket, isOnline]);
|
||||
|
||||
const sortFns: Record<string, (a: ClientRecord, b: ClientRecord) => number> = {
|
||||
enable: (a, b) => Number(a.enable) - Number(b.enable),
|
||||
email: (a, b) => (a.email || '').localeCompare(b.email || ''),
|
||||
inboundIds: (a, b) => (a.inboundIds?.length || 0) - (b.inboundIds?.length || 0),
|
||||
traffic: (a, b) => {
|
||||
const ua = (a.traffic?.up || 0) + (a.traffic?.down || 0);
|
||||
const ub = (b.traffic?.up || 0) + (b.traffic?.down || 0);
|
||||
return ua - ub;
|
||||
},
|
||||
remaining: (a, b) => {
|
||||
const ra = (a.totalGB || 0) > 0 ? (a.totalGB || 0) - ((a.traffic?.up || 0) + (a.traffic?.down || 0)) : Infinity;
|
||||
const rb = (b.totalGB || 0) > 0 ? (b.totalGB || 0) - ((b.traffic?.up || 0) + (b.traffic?.down || 0)) : Infinity;
|
||||
return ra - rb;
|
||||
},
|
||||
expiryTime: (a, b) => {
|
||||
const ea = (a.expiryTime ?? 0) > 0 ? (a.expiryTime ?? 0) : Infinity;
|
||||
const eb = (b.expiryTime ?? 0) > 0 ? (b.expiryTime ?? 0) : Infinity;
|
||||
return ea - eb;
|
||||
},
|
||||
};
|
||||
|
||||
const sortedClients = useMemo(() => {
|
||||
if (!sortColumn || !sortOrder) return filteredClients;
|
||||
const fn = sortFns[sortColumn];
|
||||
if (!fn) return filteredClients;
|
||||
const sorted = [...filteredClients].sort(fn);
|
||||
return sortOrder === 'descend' ? sorted.reverse() : sorted;
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [filteredClients, sortColumn, sortOrder]);
|
||||
// Sort is server-side now; the page already arrives in the requested
|
||||
// order, so we just hand it through.
|
||||
const sortedClients = filteredClients;
|
||||
|
||||
function trafficLabel(row: ClientRecord) {
|
||||
const t0 = row.traffic;
|
||||
@@ -341,10 +308,15 @@ export default function ClientsPage() {
|
||||
setFormOpen(true);
|
||||
}
|
||||
|
||||
function onEdit(row: ClientRecord) {
|
||||
async function onEdit(row: ClientRecord) {
|
||||
setFormMode('edit');
|
||||
setEditingClient({ ...row });
|
||||
setEditingAttachedIds(Array.isArray(row.inboundIds) ? [...row.inboundIds] : []);
|
||||
// Paged list omits per-client secrets to keep the row payload tiny;
|
||||
// edit needs them, so fetch the full record first.
|
||||
const full = await hydrate(row.email);
|
||||
const merged: ClientRecord = full ? { ...row, ...full.client } : { ...row };
|
||||
setEditingClient(merged);
|
||||
const ids = full?.inboundIds ?? (Array.isArray(row.inboundIds) ? row.inboundIds : []);
|
||||
setEditingAttachedIds([...ids]);
|
||||
setFormOpen(true);
|
||||
}
|
||||
|
||||
@@ -379,13 +351,15 @@ export default function ClientsPage() {
|
||||
});
|
||||
}
|
||||
|
||||
function onShowInfo(row: ClientRecord) {
|
||||
setInfoClient(row);
|
||||
async function onShowInfo(row: ClientRecord) {
|
||||
const full = await hydrate(row.email);
|
||||
setInfoClient(full ? { ...row, ...full.client, inboundIds: full.inboundIds } : row);
|
||||
setInfoOpen(true);
|
||||
}
|
||||
|
||||
function onShowQr(row: ClientRecord) {
|
||||
setQrClient(row);
|
||||
async function onShowQr(row: ClientRecord) {
|
||||
const full = await hydrate(row.email);
|
||||
setQrClient(full ? { ...row, ...full.client, inboundIds: full.inboundIds } : row);
|
||||
setQrOpen(true);
|
||||
}
|
||||
|
||||
@@ -595,10 +569,11 @@ export default function ClientsPage() {
|
||||
const tablePagination = {
|
||||
current: currentPage,
|
||||
pageSize: tablePageSize,
|
||||
total: sortedClients.length,
|
||||
showSizeChanger: sortedClients.length > 10,
|
||||
pageSizeOptions: ['10', '20', '50', '100'],
|
||||
hideOnSinglePage: sortedClients.length <= tablePageSize,
|
||||
total: filtered,
|
||||
showSizeChanger: filtered > 10,
|
||||
pageSizeOptions: ['10', '25', '50', '100', '200'],
|
||||
hideOnSinglePage: filtered <= tablePageSize,
|
||||
showTotal: (n: number) => `${n}`,
|
||||
};
|
||||
|
||||
const rowSelection = {
|
||||
|
||||
@@ -60,7 +60,7 @@ import { DBInbound } from '@/models/dbinbound.js';
|
||||
import FinalMaskForm from '@/components/FinalMaskForm';
|
||||
import DateTimePicker from '@/components/DateTimePicker';
|
||||
import JsonEditor from '@/components/JsonEditor';
|
||||
import { useNodes, type NodeRecord } from '@/hooks/useNodes';
|
||||
import type { NodeRecord } from '@/hooks/useNodes';
|
||||
import './InboundFormModal.css';
|
||||
|
||||
const { TextArea } = Input;
|
||||
@@ -73,6 +73,7 @@ interface InboundFormModalProps {
|
||||
mode: 'add' | 'edit';
|
||||
dbInbound: any;
|
||||
dbInbounds: any[];
|
||||
availableNodes?: NodeRecord[];
|
||||
}
|
||||
|
||||
const TRAFFIC_RESETS = ['never', 'hourly', 'daily', 'weekly', 'monthly'];
|
||||
@@ -156,10 +157,10 @@ export default function InboundFormModal({
|
||||
mode,
|
||||
dbInbound,
|
||||
dbInbounds,
|
||||
availableNodes,
|
||||
}: InboundFormModalProps) {
|
||||
const { t } = useTranslation();
|
||||
const [messageApi, messageContextHolder] = message.useMessage();
|
||||
const { nodes: availableNodes } = useNodes();
|
||||
const selectableNodes = useMemo(
|
||||
() => (availableNodes || []).filter((n: NodeRecord) => n.enable),
|
||||
[availableNodes],
|
||||
|
||||
@@ -72,6 +72,7 @@ export default function InboundsPage() {
|
||||
ipLimitEnable,
|
||||
remarkModel,
|
||||
refresh,
|
||||
hydrateInbound,
|
||||
fetchDefaultSettings,
|
||||
applyTrafficEvent,
|
||||
applyClientStatsEvent,
|
||||
@@ -259,18 +260,24 @@ export default function InboundsPage() {
|
||||
});
|
||||
}, [subSettings, openText]);
|
||||
|
||||
const exportAllLinks = useCallback(() => {
|
||||
const exportAllLinks = useCallback(async () => {
|
||||
const hydrated = await Promise.all(
|
||||
(dbInbounds as any[]).map((ib) => hydrateInbound(ib.id).then((r) => r ?? ib)),
|
||||
);
|
||||
const out: string[] = [];
|
||||
for (const ib of dbInbounds as any[]) {
|
||||
for (const ib of hydrated) {
|
||||
const projected = checkFallback(ib);
|
||||
out.push(projected.genInboundLinks(remarkModel, hostOverrideFor(ib)));
|
||||
}
|
||||
openText({ title: 'Export all inbound links', content: out.join('\r\n'), fileName: 'All-Inbounds' });
|
||||
}, [dbInbounds, checkFallback, remarkModel, hostOverrideFor, openText]);
|
||||
}, [dbInbounds, hydrateInbound, checkFallback, remarkModel, hostOverrideFor, openText]);
|
||||
|
||||
const exportAllSubs = useCallback(() => {
|
||||
const exportAllSubs = useCallback(async () => {
|
||||
const hydrated = await Promise.all(
|
||||
(dbInbounds as any[]).map((ib) => hydrateInbound(ib.id).then((r) => r ?? ib)),
|
||||
);
|
||||
const out: string[] = [];
|
||||
for (const ib of dbInbounds as any[]) {
|
||||
for (const ib of hydrated) {
|
||||
const inbound = ib.toInbound();
|
||||
const clients = inbound?.clients || [];
|
||||
for (const c of clients) {
|
||||
@@ -280,7 +287,7 @@ export default function InboundsPage() {
|
||||
}
|
||||
}
|
||||
openText({ title: 'Export all subscription links', content: [...new Set(out)].join('\r\n'), fileName: 'All-Inbounds-Subs' });
|
||||
}, [dbInbounds, subSettings, openText]);
|
||||
}, [dbInbounds, hydrateInbound, subSettings, openText]);
|
||||
|
||||
const importInbound = useCallback(() => {
|
||||
openPrompt({
|
||||
@@ -395,42 +402,51 @@ export default function InboundsPage() {
|
||||
}
|
||||
}, [modal, importInbound, exportAllLinks, exportAllSubs, refresh, messageApi]);
|
||||
|
||||
const onRowAction = useCallback(({ key, dbInbound }: { key: RowAction; dbInbound: any }) => {
|
||||
const onRowAction = useCallback(async ({ key, dbInbound }: { key: RowAction; dbInbound: any }) => {
|
||||
// Actions that touch per-client secrets (uuid, password, flow, ...) need
|
||||
// the full payload that the slim list view does not ship. Hydrate first
|
||||
// and then operate on the rehydrated record.
|
||||
const hydratingKeys: RowAction[] = ['edit', 'showInfo', 'qrcode', 'export', 'subs', 'clipboard', 'clone'];
|
||||
let target = dbInbound;
|
||||
if (hydratingKeys.includes(key)) {
|
||||
const hydrated = await hydrateInbound(dbInbound.id);
|
||||
if (hydrated) target = hydrated;
|
||||
}
|
||||
switch (key) {
|
||||
case 'edit':
|
||||
openEdit(dbInbound);
|
||||
openEdit(target);
|
||||
break;
|
||||
case 'showInfo':
|
||||
setInfoDbInbound(checkFallback(dbInbound));
|
||||
setInfoClientIndex(findClientIndex(dbInbound, null));
|
||||
setInfoDbInbound(checkFallback(target));
|
||||
setInfoClientIndex(findClientIndex(target, null));
|
||||
setInfoOpen(true);
|
||||
break;
|
||||
case 'qrcode':
|
||||
setQrDbInbound(checkFallback(dbInbound));
|
||||
setQrDbInbound(checkFallback(target));
|
||||
setQrOpen(true);
|
||||
break;
|
||||
case 'export':
|
||||
exportInboundLinks(dbInbound);
|
||||
exportInboundLinks(target);
|
||||
break;
|
||||
case 'subs':
|
||||
exportInboundSubs(dbInbound);
|
||||
exportInboundSubs(target);
|
||||
break;
|
||||
case 'clipboard':
|
||||
exportInboundClipboard(dbInbound);
|
||||
exportInboundClipboard(target);
|
||||
break;
|
||||
case 'delete':
|
||||
confirmDelete(dbInbound);
|
||||
confirmDelete(target);
|
||||
break;
|
||||
case 'resetTraffic':
|
||||
confirmResetTraffic(dbInbound);
|
||||
confirmResetTraffic(target);
|
||||
break;
|
||||
case 'clone':
|
||||
confirmClone(dbInbound);
|
||||
confirmClone(target);
|
||||
break;
|
||||
default:
|
||||
messageApi.info(`Action "${key}" — coming in a later 5f subphase`);
|
||||
}
|
||||
}, [openEdit, checkFallback, findClientIndex, exportInboundLinks, exportInboundSubs, exportInboundClipboard, confirmDelete, confirmResetTraffic, confirmClone, messageApi]);
|
||||
}, [hydrateInbound, openEdit, checkFallback, findClientIndex, exportInboundLinks, exportInboundSubs, exportInboundClipboard, confirmDelete, confirmResetTraffic, confirmClone, messageApi]);
|
||||
|
||||
const basePath = (typeof window !== 'undefined' && window.X_UI_BASE_PATH) || '';
|
||||
const requestUri = typeof window !== 'undefined' ? window.location.pathname : '';
|
||||
@@ -508,6 +524,7 @@ export default function InboundsPage() {
|
||||
mode={formMode}
|
||||
dbInbound={formDbInbound}
|
||||
dbInbounds={dbInbounds as any[]}
|
||||
availableNodes={nodesList}
|
||||
/>
|
||||
<InboundInfoModal
|
||||
open={infoOpen}
|
||||
|
||||
@@ -206,7 +206,7 @@ export function useInbounds() {
|
||||
if (refreshingRef.current) return;
|
||||
refreshingRef.current = true;
|
||||
try {
|
||||
const msg = await HttpUtil.get('/panel/api/inbounds/list');
|
||||
const msg = await HttpUtil.get('/panel/api/inbounds/list/slim');
|
||||
if (!msg?.success) return;
|
||||
await fetchLastOnlineMap();
|
||||
await fetchOnlineUsers();
|
||||
@@ -216,6 +216,26 @@ export function useInbounds() {
|
||||
}
|
||||
}, [fetchLastOnlineMap, fetchOnlineUsers, setInbounds]);
|
||||
|
||||
// hydrateInbound fetches the full inbound (including settings.clients with
|
||||
// uuid/password/flow/etc.) and swaps it into the cached list. Use this
|
||||
// before opening edit / info / qr / export / clone flows — refresh() loads
|
||||
// the slim list which doesn't carry per-client secrets.
|
||||
const hydrateInbound = useCallback(async (id: number) => {
|
||||
const msg = await HttpUtil.get(`/panel/api/inbounds/get/${id}`);
|
||||
if (!msg?.success || !msg.obj) return null;
|
||||
const full = msg.obj as { id: number; protocol: string };
|
||||
const dbInbound = new DBInbound(full) as DBInboundInstance;
|
||||
setDbInbounds((prev) => {
|
||||
const next = prev.map((row) => (
|
||||
(row as unknown as { id: number }).id === id ? dbInbound : row
|
||||
));
|
||||
dbInboundsRef.current = next;
|
||||
return next;
|
||||
});
|
||||
rebuildClientCount();
|
||||
return dbInbound;
|
||||
}, [rebuildClientCount]);
|
||||
|
||||
const applyTrafficEvent = useCallback(
|
||||
(payload: unknown) => {
|
||||
if (!payload || typeof payload !== 'object') return;
|
||||
@@ -340,6 +360,7 @@ export function useInbounds() {
|
||||
ipLimitEnable,
|
||||
pageSize,
|
||||
refresh,
|
||||
hydrateInbound,
|
||||
fetchDefaultSettings,
|
||||
applyTrafficEvent,
|
||||
applyClientStatsEvent,
|
||||
|
||||
@@ -38,7 +38,9 @@ export default function GeneralTab({ allSetting, updateSetting }: GeneralTabProp
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
(async () => {
|
||||
const msg = await HttpUtil.get('/panel/api/inbounds/list') as ApiMsg<{
|
||||
// /options is the slim picker-shaped endpoint — it skips the heavy
|
||||
// per-client settings and clientStats payloads that /list ships.
|
||||
const msg = await HttpUtil.get('/panel/api/inbounds/options') as ApiMsg<{
|
||||
tag: string; protocol: string; port: number;
|
||||
}[]>;
|
||||
if (cancelled) return;
|
||||
|
||||
Reference in New Issue
Block a user