useInbounds.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  1. import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
  2. import { useQuery, useQueryClient } from '@tanstack/react-query';
  3. import { HttpUtil } from '@/utils';
  4. import { parseMsg } from '@/utils/zodValidate';
  5. import { DBInbound, coerceInboundJsonField } from '@/models/dbinbound';
  6. import type { ClientStats, DBInboundInit } from '@/models/dbinbound';
  7. import { Protocols } from '@/schemas/primitives';
  8. import { isSSMultiUser } from '@/lib/xray/protocol-capabilities';
  9. import { setDatepicker } from '@/hooks/useDatepicker';
  10. import { keys } from '@/api/queryKeys';
  11. import { SlimInboundListSchema, LastOnlineMapSchema, InboundDetailSchema } from '@/schemas/inbound';
  12. import { OnlinesSchema, OnlineByNodeSchema, ActiveInboundsByNodeSchema } from '@/schemas/client';
  13. import { DefaultsPayloadSchema, type DefaultsPayload } from '@/schemas/defaults';
  14. import type { InboundSpeedEntry } from './list/types';
  15. import { TRAFFIC_POLL_INTERVAL_S } from '@/lib/traffic/poll-interval';
  16. export interface SubSettings {
  17. enable: boolean;
  18. subTitle: string;
  19. subURI: string;
  20. subJsonURI: string;
  21. subJsonEnable: boolean;
  22. // Configured public host (Sub Domain, else Web Domain) used as the share/QR
  23. // link host when the panel is reached on a loopback address. Empty if neither
  24. // is set.
  25. publicHost: string;
  26. }
  27. type DBInboundInstance = InstanceType<typeof DBInbound>;
  28. // Speed is delta-derived, so it can't be recomputed until the first poll after
  29. // mount; navigating away and back would otherwise blank the column for up to one
  30. // poll. Cache the last speed map across mounts (module scope) and reseed from it
  31. // while recent, so returning to the page shows the last throughput immediately
  32. // and the next poll refreshes it.
  33. const SPEED_CACHE_TTL_MS = 15000;
  34. let inboundSpeedCache: { at: number; data: Record<number, InboundSpeedEntry> } = {
  35. at: 0,
  36. data: {},
  37. };
  38. interface TrafficDelta {
  39. Tag: string;
  40. Up: number;
  41. Down: number;
  42. IsInbound?: boolean;
  43. }
  44. interface ClientRollup {
  45. clients: number;
  46. active: string[];
  47. deactive: string[];
  48. depleted: string[];
  49. expiring: string[];
  50. online: string[];
  51. comments: Map<string, string>;
  52. }
  53. const TRACKED_PROTOCOLS: readonly string[] = [
  54. Protocols.VMESS,
  55. Protocols.VLESS,
  56. Protocols.TROJAN,
  57. Protocols.SHADOWSOCKS,
  58. Protocols.HYSTERIA,
  59. Protocols.WIREGUARD,
  60. Protocols.MTPROTO,
  61. Protocols.AMNEZIAWG,
  62. Protocols.TUIC,
  63. ];
  64. async function fetchSlimInbounds(): Promise<unknown[]> {
  65. const msg = await HttpUtil.get('/panel/api/inbounds/list/slim', undefined, { silent: true });
  66. if (!msg?.success) throw new Error(msg?.msg || 'Failed to fetch inbounds');
  67. const validated = parseMsg(msg, SlimInboundListSchema, 'inbounds/list/slim');
  68. return Array.isArray(validated.obj) ? validated.obj : [];
  69. }
  70. async function fetchOnlineClients(): Promise<string[]> {
  71. const msg = await HttpUtil.post('/panel/api/clients/onlines', undefined, { silent: true });
  72. if (!msg?.success) throw new Error(msg?.msg || 'Failed to fetch onlines');
  73. const validated = parseMsg(msg, OnlinesSchema, 'clients/onlines');
  74. return Array.isArray(validated.obj) ? validated.obj : [];
  75. }
  76. // Online emails grouped by the panelGuid of the node that physically hosts each
  77. // client, used to scope the per-inbound online rollup so a client online on one
  78. // node is not shown online on every node's inbounds — and a client on a
  79. // sub-node is attributed to that sub-node, not the node it syncs through (#4983).
  80. async function fetchOnlineClientsByGuid(): Promise<Record<string, string[]>> {
  81. const msg = await HttpUtil.post('/panel/api/clients/onlinesByGuid', undefined, { silent: true });
  82. if (!msg?.success) throw new Error(msg?.msg || 'Failed to fetch onlinesByGuid');
  83. const validated = parseMsg(msg, OnlineByNodeSchema, 'clients/onlinesByGuid');
  84. return validated.obj && typeof validated.obj === 'object'
  85. ? (validated.obj as Record<string, string[]>)
  86. : {};
  87. }
  88. // Inbound tags that carried traffic recently, grouped by node (local = key 0).
  89. // Pairs with the per-node online map so a client attached to several inbounds
  90. // is only marked online on the ones that actually moved bytes — Xray's
  91. // user-level stat can't attribute traffic to a single inbound on its own.
  92. async function fetchActiveInboundsByNode(): Promise<Record<string, string[]>> {
  93. const msg = await HttpUtil.post('/panel/api/clients/activeInbounds', undefined, { silent: true });
  94. if (!msg?.success) throw new Error(msg?.msg || 'Failed to fetch activeInbounds');
  95. const validated = parseMsg(msg, ActiveInboundsByNodeSchema, 'clients/activeInbounds');
  96. return validated.obj && typeof validated.obj === 'object'
  97. ? (validated.obj as Record<string, string[]>)
  98. : {};
  99. }
  100. function toGuidOnlineMap(data: Record<string, string[]>): Map<string, Set<string>> {
  101. const map = new Map<string, Set<string>>();
  102. for (const [key, emails] of Object.entries(data)) {
  103. if (!Array.isArray(emails)) continue;
  104. map.set(key, new Set(emails));
  105. }
  106. return map;
  107. }
  108. async function fetchLastOnlineMap(): Promise<Record<string, number>> {
  109. const msg = await HttpUtil.post('/panel/api/clients/lastOnline', undefined, { silent: true });
  110. if (!msg?.success) throw new Error(msg?.msg || 'Failed to fetch lastOnline');
  111. const validated = parseMsg(msg, LastOnlineMapSchema, 'clients/lastOnline');
  112. return validated.obj && typeof validated.obj === 'object' ? validated.obj : {};
  113. }
  114. async function fetchDefaultSettings(): Promise<DefaultsPayload> {
  115. const msg = await HttpUtil.post('/panel/api/setting/defaultSettings', undefined, {
  116. silent: true,
  117. });
  118. if (!msg?.success) throw new Error(msg?.msg || 'Failed to fetch defaults');
  119. const validated = parseMsg(msg, DefaultsPayloadSchema, 'setting/defaultSettings');
  120. return validated.obj ?? {};
  121. }
  122. export function useInbounds() {
  123. const queryClient = useQueryClient();
  124. const slimQuery = useQuery({
  125. queryKey: keys.inbounds.slim(),
  126. queryFn: fetchSlimInbounds,
  127. staleTime: Infinity,
  128. });
  129. const onlinesQuery = useQuery({
  130. queryKey: keys.clients.onlines(),
  131. queryFn: fetchOnlineClients,
  132. staleTime: Infinity,
  133. });
  134. const onlinesByGuidQuery = useQuery({
  135. queryKey: keys.clients.onlinesByGuid(),
  136. queryFn: fetchOnlineClientsByGuid,
  137. staleTime: Infinity,
  138. });
  139. const activeInboundsQuery = useQuery({
  140. queryKey: keys.clients.activeInbounds(),
  141. queryFn: fetchActiveInboundsByNode,
  142. staleTime: Infinity,
  143. });
  144. const lastOnlineQuery = useQuery({
  145. queryKey: keys.clients.lastOnline(),
  146. queryFn: fetchLastOnlineMap,
  147. staleTime: Infinity,
  148. });
  149. const defaultsQuery = useQuery({
  150. queryKey: keys.settings.defaults(),
  151. queryFn: fetchDefaultSettings,
  152. staleTime: Infinity,
  153. });
  154. const defaults = defaultsQuery.data ?? {};
  155. const expireDiff = (defaults.expireDiff ?? 0) * 86400000;
  156. const trafficDiff = (defaults.trafficDiff ?? 0) * 1073741824;
  157. const tgBotEnable = !!defaults.tgBotEnable;
  158. const ipLimitEnable = !!defaults.ipLimitEnable;
  159. const pageSize = defaults.pageSize ?? 0;
  160. const datepicker = (defaults.datepicker as 'gregorian' | 'jalalian') || 'gregorian';
  161. const subSettings: SubSettings = useMemo(
  162. () => ({
  163. enable: !!defaults.subEnable,
  164. subTitle: defaults.subTitle || '',
  165. subURI: defaults.subURI || '',
  166. subJsonURI: defaults.subJsonURI || '',
  167. subJsonEnable: !!defaults.subJsonEnable,
  168. publicHost: defaults.subDomain || defaults.webDomain || '',
  169. }),
  170. [
  171. defaults.subEnable,
  172. defaults.subTitle,
  173. defaults.subURI,
  174. defaults.subJsonURI,
  175. defaults.subJsonEnable,
  176. defaults.subDomain,
  177. defaults.webDomain,
  178. ],
  179. );
  180. useEffect(() => {
  181. if (defaults.datepicker) setDatepicker(datepicker);
  182. }, [datepicker, defaults.datepicker]);
  183. // dbInbounds mirrors the slim query data wrapped as DBInbound instances. The
  184. // WS handlers rebuild only the rows they touch, so no refetch is needed.
  185. const [dbInbounds, setDbInbounds] = useState<DBInboundInstance[]>([]);
  186. const dbInboundsRef = useRef<DBInboundInstance[]>([]);
  187. useEffect(() => {
  188. dbInboundsRef.current = dbInbounds;
  189. });
  190. const [inboundSpeed, setInboundSpeed] = useState<Record<number, InboundSpeedEntry>>(() =>
  191. Date.now() - inboundSpeedCache.at < SPEED_CACHE_TTL_MS ? inboundSpeedCache.data : {},
  192. );
  193. useEffect(() => {
  194. inboundSpeedCache = { at: Date.now(), data: inboundSpeed };
  195. }, [inboundSpeed]);
  196. const [onlineClients, setOnlineClients] = useState<string[]>([]);
  197. // Online emails keyed by the hosting node's panelGuid. The rollup reads this
  198. // so each inbound only counts clients online on the node that physically
  199. // hosts it, attributing a sub-node's clients to that sub-node (#4983).
  200. const [onlineByGuid, setOnlineByGuid] = useState<Map<string, Set<string>>>(() => new Map());
  201. // Recently-active inbound tags keyed by the hosting node's panelGuid. A GUID
  202. // missing from this map means "no per-inbound activity reported" (e.g. remote
  203. // nodes), so the rollup leaves that node's inbounds ungated and falls back to
  204. // the email signal. A present GUID gates: a client only counts online on an
  205. // inbound whose tag carried traffic this window.
  206. const [activeByGuid, setActiveByGuid] = useState<Map<string, Set<string>>>(() => new Map());
  207. const [lastOnlineMap, setLastOnlineMap] = useState<Record<string, number>>({});
  208. const rollupClients = useCallback(
  209. (
  210. dbInbound: DBInboundInstance,
  211. inbound: { clients?: { email?: string; enable?: boolean; comment?: string }[] },
  212. ): ClientRollup => {
  213. const clientStats = Array.isArray((dbInbound as { clientStats?: unknown }).clientStats)
  214. ? (
  215. dbInbound as unknown as {
  216. clientStats: {
  217. email: string;
  218. total: number;
  219. up: number;
  220. down: number;
  221. expiryTime: number;
  222. }[];
  223. }
  224. ).clientStats
  225. : [];
  226. const clients = inbound?.clients || [];
  227. const active: string[] = [];
  228. const deactive: string[] = [];
  229. const depleted: string[] = [];
  230. const expiring: string[] = [];
  231. const online: string[] = [];
  232. const comments = new Map<string, string>();
  233. const now = Date.now();
  234. // Attribution key: the GUID of the node that physically hosts this
  235. // inbound. Local inbounds carry the panel's own GUID (filled server-side);
  236. // a node-managed inbound carries its origin node's GUID, or falls back to
  237. // the master-local synthetic id for an old-build node without one (#4983).
  238. const guid =
  239. dbInbound.originNodeGuid || (dbInbound.nodeId != null ? `node:${dbInbound.nodeId}` : '');
  240. const nodeOnline = onlineByGuid.get(guid);
  241. // A node absent from the active map reports no per-inbound activity, so
  242. // leave its inbounds ungated. When present, only mark a client online on
  243. // this inbound if its tag actually carried traffic — that's what stops a
  244. // multi-inbound client lighting up every inbound it's attached to.
  245. const activeForNode = activeByGuid.get(guid);
  246. const inboundActive =
  247. activeForNode === undefined || !dbInbound.tag || activeForNode.has(dbInbound.tag);
  248. if (dbInbound.enable) {
  249. const statsByEmail = new Map<
  250. string,
  251. { email: string; total: number; up: number; down: number; expiryTime: number }
  252. >();
  253. for (const stats of clientStats) {
  254. if (stats.email) statsByEmail.set(stats.email.toLowerCase(), stats);
  255. }
  256. for (const client of clients) {
  257. if (client.comment && client.email) comments.set(client.email, client.comment);
  258. if (!client.email) continue;
  259. const stats = statsByEmail.get(client.email.toLowerCase());
  260. const exhausted =
  261. stats != null && stats.total > 0 && stats.up + stats.down >= stats.total;
  262. const expired = stats != null && stats.expiryTime > 0 && stats.expiryTime <= now;
  263. if (expired || exhausted) {
  264. depleted.push(client.email);
  265. continue;
  266. }
  267. if (!client.enable) {
  268. deactive.push(client.email);
  269. continue;
  270. }
  271. active.push(client.email);
  272. if (inboundActive && nodeOnline?.has(client.email)) online.push(client.email);
  273. if (stats) {
  274. const expiringSoon =
  275. (stats.expiryTime > 0 && stats.expiryTime - now < expireDiff) ||
  276. (stats.total > 0 && stats.total - (stats.up + stats.down) < trafficDiff);
  277. if (expiringSoon) expiring.push(client.email);
  278. }
  279. }
  280. } else {
  281. for (const client of clients) {
  282. if (client.email) deactive.push(client.email);
  283. }
  284. }
  285. return {
  286. clients: clients.length,
  287. active,
  288. deactive,
  289. depleted,
  290. expiring,
  291. online,
  292. comments,
  293. };
  294. },
  295. [onlineByGuid, activeByGuid, expireDiff, trafficDiff],
  296. );
  297. // Every write to a DBInbound row also replaces the dbInbounds array, so this
  298. // recomputes on both a refetch and a WS-merged stats update.
  299. const clientCount = useMemo(() => {
  300. const counts: Record<number, ClientRollup> = {};
  301. for (const dbInbound of dbInbounds) {
  302. const protocol = dbInbound.protocol;
  303. if (!TRACKED_PROTOCOLS.includes(protocol)) continue;
  304. const settings = coerceInboundJsonField(dbInbound.settings) as {
  305. method?: string;
  306. clients?: Array<{ email?: string; enable?: boolean; comment?: string }>;
  307. };
  308. if (protocol === Protocols.SHADOWSOCKS && !isSSMultiUser({ protocol, settings })) continue;
  309. counts[dbInbound.id] = rollupClients(dbInbound, { clients: settings.clients });
  310. }
  311. return counts;
  312. }, [dbInbounds, rollupClients]);
  313. // Adopting fetched data during render (rather than in an effect) keeps the
  314. // list from painting one frame of the previous data after a refetch.
  315. const [syncedSlim, setSyncedSlim] = useState<unknown>();
  316. if (slimQuery.data && slimQuery.data !== syncedSlim) {
  317. setSyncedSlim(slimQuery.data);
  318. setDbInbounds(
  319. (slimQuery.data as { protocol: string; id: number }[]).map(
  320. (row) => new DBInbound(row) as DBInboundInstance,
  321. ),
  322. );
  323. }
  324. const [syncedOnlines, setSyncedOnlines] = useState<unknown>();
  325. if (onlinesQuery.data && onlinesQuery.data !== syncedOnlines) {
  326. setSyncedOnlines(onlinesQuery.data);
  327. setOnlineClients(onlinesQuery.data);
  328. }
  329. const [syncedOnlinesByGuid, setSyncedOnlinesByGuid] = useState<unknown>();
  330. if (onlinesByGuidQuery.data && onlinesByGuidQuery.data !== syncedOnlinesByGuid) {
  331. setSyncedOnlinesByGuid(onlinesByGuidQuery.data);
  332. setOnlineByGuid(toGuidOnlineMap(onlinesByGuidQuery.data));
  333. }
  334. const [syncedActiveInbounds, setSyncedActiveInbounds] = useState<unknown>();
  335. if (activeInboundsQuery.data && activeInboundsQuery.data !== syncedActiveInbounds) {
  336. setSyncedActiveInbounds(activeInboundsQuery.data);
  337. setActiveByGuid(toGuidOnlineMap(activeInboundsQuery.data));
  338. }
  339. const [syncedLastOnline, setSyncedLastOnline] = useState<unknown>();
  340. if (lastOnlineQuery.data && lastOnlineQuery.data !== syncedLastOnline) {
  341. setSyncedLastOnline(lastOnlineQuery.data);
  342. setLastOnlineMap(lastOnlineQuery.data);
  343. }
  344. const fetched =
  345. (slimQuery.data !== undefined || slimQuery.isError) &&
  346. (defaultsQuery.data !== undefined || defaultsQuery.isError);
  347. const fetchErrorSource = slimQuery.error || defaultsQuery.error;
  348. const fetchError = fetchErrorSource ? (fetchErrorSource as Error).message : '';
  349. const refresh = useCallback(async () => {
  350. // Invalidate at the inbounds root so both `slim` (this page's list)
  351. // and `options` (the Clients page's inbound picker) refetch. Without
  352. // the options bucket, a freshly-created inbound stays invisible in
  353. // the client add/edit modal until a full page reload. The xray config
  354. // response carries inboundTags for the routing-rule tag picker, so it
  355. // needs invalidating too or that list stays stale until a hard refresh.
  356. await Promise.all([
  357. queryClient.invalidateQueries({ queryKey: keys.inbounds.root() }),
  358. queryClient.invalidateQueries({ queryKey: keys.clients.onlines() }),
  359. queryClient.invalidateQueries({ queryKey: keys.clients.onlinesByGuid() }),
  360. queryClient.invalidateQueries({ queryKey: keys.clients.activeInbounds() }),
  361. queryClient.invalidateQueries({ queryKey: keys.clients.lastOnline() }),
  362. queryClient.invalidateQueries({ queryKey: keys.xray.config() }),
  363. ]);
  364. }, [queryClient]);
  365. // hydrateInbound fetches the full inbound (including settings.clients with
  366. // uuid/password/flow/etc.) and swaps it into the cached list. Use this
  367. // before opening edit / info / qr / export / clone flows — refresh() loads
  368. // the slim list which doesn't carry per-client secrets.
  369. const hydrateInbound = useCallback(async (id: number) => {
  370. const msg = await HttpUtil.get(`/panel/api/inbounds/get/${id}`);
  371. if (!msg?.success || !msg.obj) return null;
  372. const validated = parseMsg(msg, InboundDetailSchema, `inbounds/get/${id}`);
  373. if (!validated.obj) return null;
  374. const dbInbound = new DBInbound(validated.obj) as DBInboundInstance;
  375. setDbInbounds((prev) => {
  376. const next = prev.map((row) =>
  377. (row as unknown as { id: number }).id === id ? dbInbound : row,
  378. );
  379. dbInboundsRef.current = next;
  380. return next;
  381. });
  382. return dbInbound;
  383. }, []);
  384. const applyTrafficEvent = useCallback((payload: unknown) => {
  385. if (!payload || typeof payload !== 'object') return;
  386. const p = payload as {
  387. traffics?: TrafficDelta[];
  388. nodeTraffics?: TrafficDelta[];
  389. onlineClients?: string[];
  390. onlineByGuid?: Record<string, string[]>;
  391. activeInbounds?: Record<string, string[]>;
  392. lastOnlineMap?: Record<string, number>;
  393. };
  394. if (Array.isArray(p.onlineClients)) {
  395. setOnlineClients(p.onlineClients);
  396. }
  397. if (p.onlineByGuid && typeof p.onlineByGuid === 'object') {
  398. setOnlineByGuid(toGuidOnlineMap(p.onlineByGuid));
  399. }
  400. if (p.activeInbounds && typeof p.activeInbounds === 'object') {
  401. setActiveByGuid(toGuidOnlineMap(p.activeInbounds));
  402. }
  403. if (p.lastOnlineMap && typeof p.lastOnlineMap === 'object') {
  404. setLastOnlineMap((prev) => ({ ...prev, ...p.lastOnlineMap! }));
  405. }
  406. // Speed arrives from two independent 5s polls: the local Xray poll sends
  407. // `traffics` (local inbounds) and the node sync sends `nodeTraffics` (node
  408. // inbounds). Each replaces speed only within its own scope so the two don't
  409. // clobber each other; an idle in-scope inbound — absent from its payload —
  410. // clears instead of showing a stale value.
  411. const applyTraffics = (
  412. traffics: TrafficDelta[],
  413. inScope: (ib: DBInboundInstance) => boolean,
  414. ) => {
  415. const byTag = new Map<string, TrafficDelta>();
  416. for (const tr of traffics) {
  417. if (!tr || typeof tr.Tag !== 'string') continue;
  418. if (tr.IsInbound === false) continue;
  419. byTag.set(tr.Tag, tr);
  420. }
  421. setInboundSpeed((prev) => {
  422. const next = { ...prev };
  423. for (const ib of dbInboundsRef.current) {
  424. if (!inScope(ib)) continue;
  425. const delta = byTag.get(ib.tag);
  426. if (delta) {
  427. next[ib.id] = {
  428. up: (delta.Up || 0) / TRAFFIC_POLL_INTERVAL_S,
  429. down: (delta.Down || 0) / TRAFFIC_POLL_INTERVAL_S,
  430. };
  431. } else {
  432. delete next[ib.id];
  433. }
  434. }
  435. return next;
  436. });
  437. };
  438. if (Array.isArray(p.traffics)) applyTraffics(p.traffics, (ib) => ib.nodeId == null);
  439. if (Array.isArray(p.nodeTraffics)) applyTraffics(p.nodeTraffics, (ib) => ib.nodeId != null);
  440. }, []);
  441. const applyClientStatsEvent = useCallback((payload: unknown) => {
  442. if (!payload || typeof payload !== 'object') return;
  443. const p = payload as {
  444. inbounds?: { id: number; up?: number; down?: number; total?: number; enable?: boolean }[];
  445. clients?: {
  446. email: string;
  447. up?: number;
  448. down?: number;
  449. total?: number;
  450. expiryTime?: number;
  451. enable?: boolean;
  452. }[];
  453. };
  454. const byId = new Map<
  455. number,
  456. { id: number; up?: number; down?: number; total?: number; enable?: boolean }
  457. >();
  458. if (Array.isArray(p.inbounds)) {
  459. for (const row of p.inbounds) {
  460. if (row && row.id != null) byId.set(row.id, row);
  461. }
  462. }
  463. const byEmail = new Map<
  464. string,
  465. {
  466. email: string;
  467. up?: number;
  468. down?: number;
  469. total?: number;
  470. expiryTime?: number;
  471. enable?: boolean;
  472. }
  473. >();
  474. if (Array.isArray(p.clients)) {
  475. for (const row of p.clients) {
  476. if (row && row.email) byEmail.set(row.email, row);
  477. }
  478. }
  479. if (byId.size === 0 && byEmail.size === 0) return;
  480. // Rows carrying an update are rebuilt rather than patched in place: the
  481. // derived clientCount only recomputes when a row's identity changes.
  482. let touched = false;
  483. const next = dbInboundsRef.current.map((ib) => {
  484. const upd = byId.get(ib.id);
  485. const stats = Array.isArray(ib.clientStats) ? ib.clientStats : null;
  486. let statsTouched = false;
  487. const nextStats =
  488. stats && byEmail.size > 0
  489. ? stats.map((stat) => {
  490. const su = byEmail.get(stat.email);
  491. if (!su) return stat;
  492. statsTouched = true;
  493. return {
  494. ...stat,
  495. up: typeof su.up === 'number' ? su.up : stat.up,
  496. down: typeof su.down === 'number' ? su.down : stat.down,
  497. total: typeof su.total === 'number' ? su.total : stat.total,
  498. expiryTime: typeof su.expiryTime === 'number' ? su.expiryTime : stat.expiryTime,
  499. enable: typeof su.enable === 'boolean' ? su.enable : stat.enable,
  500. } as ClientStats;
  501. })
  502. : null;
  503. if (!upd && !statsTouched) return ib;
  504. touched = true;
  505. const row = new DBInbound(ib as DBInboundInit) as DBInboundInstance;
  506. if (upd) {
  507. if (typeof upd.up === 'number') row.up = upd.up;
  508. if (typeof upd.down === 'number') row.down = upd.down;
  509. if (typeof upd.total === 'number') row.total = upd.total;
  510. if (typeof upd.enable === 'boolean') row.enable = upd.enable;
  511. }
  512. if (statsTouched && nextStats) row.clientStats = nextStats;
  513. return row;
  514. });
  515. if (!touched) return;
  516. dbInboundsRef.current = next;
  517. setDbInbounds(next);
  518. }, []);
  519. const totals = useMemo(() => {
  520. let up = 0;
  521. let down = 0;
  522. for (const ib of dbInbounds) {
  523. const rec = ib as unknown as { up?: number; down?: number };
  524. up += rec.up || 0;
  525. down += rec.down || 0;
  526. }
  527. return { up, down };
  528. }, [dbInbounds]);
  529. return {
  530. fetched,
  531. fetchError,
  532. dbInbounds,
  533. clientCount,
  534. onlineClients,
  535. lastOnlineMap,
  536. inboundSpeed,
  537. totals,
  538. expireDiff,
  539. trafficDiff,
  540. subSettings,
  541. datepicker,
  542. tgBotEnable,
  543. ipLimitEnable,
  544. pageSize,
  545. refresh,
  546. hydrateInbound,
  547. applyTrafficEvent,
  548. applyClientStatsEvent,
  549. };
  550. }