| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382 |
- import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
- import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
- import { z } from 'zod';
- import { HttpUtil, Msg, PromiseUtil } from '@/utils';
- import { parseMsg } from '@/utils/zodValidate';
- import { keys } from '@/api/queryKeys';
- import {
- OutboundTrafficListSchema,
- OutboundTestResultSchema,
- XrayConfigPayloadSchema,
- XraySettingsValueSchema,
- type OutboundTestResult,
- type OutboundTrafficRow,
- } from '@/schemas/xray';
- const DIRTY_POLL_MS = 1000;
- const DEFAULT_TEST_URL = 'https://www.google.com/generate_204';
- export type { OutboundTrafficRow, OutboundTestResult };
- export type XraySettingsValue = z.infer<typeof XraySettingsValueSchema>;
- export interface OutboundTestState {
- testing?: boolean;
- result?: OutboundTestResult | null;
- mode?: string;
- }
- export type SetTemplate = (
- next: XraySettingsValue | null | ((prev: XraySettingsValue | null) => XraySettingsValue | null),
- ) => void;
- export interface UseXraySettingResult {
- fetched: boolean;
- spinning: boolean;
- saveDisabled: boolean;
- fetchError: string;
- xraySetting: string;
- setXraySetting: (next: string) => void;
- templateSettings: XraySettingsValue | null;
- setTemplateSettings: SetTemplate;
- outboundTestUrl: string;
- setOutboundTestUrl: (v: string) => void;
- inboundTags: string[];
- clientReverseTags: string[];
- restartResult: string;
- outboundsTraffic: OutboundTrafficRow[];
- outboundTestStates: Record<number, OutboundTestState>;
- testingAll: boolean;
- fetchAll: () => Promise<void>;
- fetchOutboundsTraffic: () => Promise<void>;
- resetOutboundsTraffic: (tag: string) => Promise<void>;
- testOutbound: (
- index: number,
- outbound: unknown,
- mode?: string,
- ) => Promise<OutboundTestResult | null>;
- testAllOutbounds: (mode?: string) => Promise<void>;
- saveAll: () => Promise<void>;
- resetToDefault: () => Promise<void>;
- restartXray: () => Promise<void>;
- }
- type XrayConfigPayload = z.infer<typeof XrayConfigPayloadSchema>;
- async function fetchXrayConfig(): Promise<XrayConfigPayload> {
- const msg = await HttpUtil.post('/panel/xray/', undefined, { silent: true });
- if (!msg?.success) throw new Error(msg?.msg || 'Failed to load xray config');
- if (typeof msg.obj !== 'string') throw new Error('Malformed xray config response: expected string');
- let parsed: unknown;
- try {
- parsed = JSON.parse(msg.obj);
- } catch (e) {
- const err = e as Error;
- throw new Error(`Malformed xray config response: ${err.message}`, { cause: e });
- }
- const result = XrayConfigPayloadSchema.safeParse(parsed);
- if (!result.success) {
- console.warn('[zod] xray/ config payload failed validation', result.error.issues);
- return parsed as XrayConfigPayload;
- }
- return result.data;
- }
- async function fetchOutboundsTraffic(): Promise<OutboundTrafficRow[]> {
- const msg = await HttpUtil.get('/panel/xray/getOutboundsTraffic', undefined, { silent: true });
- if (!msg?.success) throw new Error(msg?.msg || 'Failed to fetch outbounds traffic');
- const validated = parseMsg(msg, OutboundTrafficListSchema, 'xray/getOutboundsTraffic');
- return Array.isArray(validated.obj) ? validated.obj : [];
- }
- export function useXraySetting(): UseXraySettingResult {
- const queryClient = useQueryClient();
- const configQuery = useQuery({
- queryKey: keys.xray.config(),
- queryFn: fetchXrayConfig,
- staleTime: Infinity,
- });
- const trafficQuery = useQuery({
- queryKey: keys.xray.outboundsTraffic(),
- queryFn: fetchOutboundsTraffic,
- staleTime: Infinity,
- });
- const [saveDisabled, setSaveDisabled] = useState(true);
- const [xraySetting, setXraySettingState] = useState('');
- const [templateSettings, setTemplateSettingsState] = useState<XraySettingsValue | null>(null);
- const [outboundTestUrl, setOutboundTestUrlState] = useState(DEFAULT_TEST_URL);
- const [inboundTags, setInboundTags] = useState<string[]>([]);
- const [clientReverseTags, setClientReverseTags] = useState<string[]>([]);
- const [restartResult, setRestartResult] = useState('');
- const [outboundTestStates, setOutboundTestStates] = useState<Record<number, OutboundTestState>>({});
- const [testingAll, setTestingAll] = useState(false);
- const oldXraySettingRef = useRef('');
- const oldOutboundTestUrlRef = useRef('');
- const syncingRef = useRef(false);
- const xraySettingRef = useRef('');
- const outboundTestUrlRef = useRef(outboundTestUrl);
- const templateSettingsRef = useRef<XraySettingsValue | null>(null);
- xraySettingRef.current = xraySetting;
- outboundTestUrlRef.current = outboundTestUrl;
- templateSettingsRef.current = templateSettings;
- // Seed local editor state from the config query. Runs on first fetch and
- // every time the query refetches (e.g. after a successful save).
- useEffect(() => {
- if (!configQuery.data) return;
- const obj = configQuery.data;
- const pretty = JSON.stringify(obj.xraySetting, null, 2);
- syncingRef.current = true;
- setXraySettingState(pretty);
- setTemplateSettingsState(obj.xraySetting);
- oldXraySettingRef.current = pretty;
- syncingRef.current = false;
- setInboundTags(obj.inboundTags || []);
- setClientReverseTags(obj.clientReverseTags || []);
- const nextUrl = obj.outboundTestUrl || DEFAULT_TEST_URL;
- setOutboundTestUrlState(nextUrl);
- oldOutboundTestUrlRef.current = nextUrl;
- setSaveDisabled(true);
- }, [configQuery.data]);
- const fetched = configQuery.data !== undefined || configQuery.isError;
- const fetchError = configQuery.error ? (configQuery.error as Error).message : '';
- const setXraySetting = useCallback((next: string) => {
- setXraySettingState(next);
- if (syncingRef.current) return;
- try {
- const parsed = JSON.parse(next);
- syncingRef.current = true;
- setTemplateSettingsState(parsed);
- syncingRef.current = false;
- } catch {
- /* ignore — wait for user to finish */
- }
- }, []);
- const setTemplateSettings: SetTemplate = useCallback((nextOrFn) => {
- setTemplateSettingsState((prev) => {
- const next = typeof nextOrFn === 'function' ? nextOrFn(prev) : nextOrFn;
- if (next == null) return next;
- if (!syncingRef.current) {
- try {
- syncingRef.current = true;
- setXraySettingState(JSON.stringify(next, null, 2));
- } finally {
- syncingRef.current = false;
- }
- }
- return next;
- });
- }, []);
- const setOutboundTestUrl = useCallback((v: string) => {
- setOutboundTestUrlState(v);
- }, []);
- const fetchAll = useCallback(async () => {
- await queryClient.invalidateQueries({ queryKey: keys.xray.config() });
- }, [queryClient]);
- const fetchOutboundsTrafficCb = useCallback(async () => {
- await queryClient.invalidateQueries({ queryKey: keys.xray.outboundsTraffic() });
- }, [queryClient]);
- const saveMut = useMutation({
- mutationFn: async () =>
- HttpUtil.post('/panel/xray/update', {
- xraySetting: xraySettingRef.current,
- outboundTestUrl: outboundTestUrlRef.current || DEFAULT_TEST_URL,
- }),
- onSuccess: (msg) => {
- if (msg?.success) queryClient.invalidateQueries({ queryKey: keys.xray.config() });
- },
- });
- const resetTrafficMut = useMutation({
- mutationFn: (tag: string) =>
- HttpUtil.post('/panel/xray/resetOutboundsTraffic', { tag }),
- onSuccess: (msg) => {
- if (msg?.success) queryClient.invalidateQueries({ queryKey: keys.xray.outboundsTraffic() });
- },
- });
- const restartMut = useMutation({
- mutationFn: async () => {
- const msg = await HttpUtil.post('/panel/api/server/restartXrayService');
- if (!msg?.success) return msg;
- await PromiseUtil.sleep(500);
- const r = await HttpUtil.get('/panel/xray/getXrayResult');
- const validated = parseMsg(r, z.string(), 'xray/getXrayResult');
- if (validated?.success) setRestartResult(validated.obj || '');
- return msg;
- },
- });
- const resetDefaultMut = useMutation({
- mutationFn: async (): Promise<Msg<XraySettingsValue>> => {
- const raw = await HttpUtil.get('/panel/setting/getDefaultJsonConfig');
- return parseMsg(raw, XraySettingsValueSchema, 'setting/getDefaultJsonConfig');
- },
- onSuccess: (msg) => {
- if (msg?.success && msg.obj) {
- const cloned = JSON.parse(JSON.stringify(msg.obj));
- setTemplateSettings(cloned);
- }
- },
- });
- const saveAll = useCallback(async () => { await saveMut.mutateAsync(); }, [saveMut]);
- const resetOutboundsTraffic = useCallback(async (tag: string) => { await resetTrafficMut.mutateAsync(tag); }, [resetTrafficMut]);
- const restartXray = useCallback(async () => { await restartMut.mutateAsync(); }, [restartMut]);
- const resetToDefault = useCallback(async () => { await resetDefaultMut.mutateAsync(); }, [resetDefaultMut]);
- const spinning = saveMut.isPending || restartMut.isPending || resetDefaultMut.isPending;
- const testOutbound = useCallback(
- async (index: number, outbound: unknown, mode = 'tcp'): Promise<OutboundTestResult | null> => {
- if (!outbound) return null;
- setOutboundTestStates((prev) => ({
- ...prev,
- [index]: { testing: true, result: null, mode },
- }));
- try {
- const raw = await HttpUtil.post('/panel/xray/testOutbound', {
- outbound: JSON.stringify(outbound),
- allOutbounds: JSON.stringify(templateSettingsRef.current?.outbounds || []),
- mode,
- });
- const msg = parseMsg(raw, OutboundTestResultSchema, 'xray/testOutbound');
- if (msg?.success && msg.obj) {
- setOutboundTestStates((prev) => ({
- ...prev,
- [index]: { testing: false, result: msg.obj },
- }));
- return msg.obj;
- }
- setOutboundTestStates((prev) => ({
- ...prev,
- [index]: {
- testing: false,
- result: { success: false, error: msg?.msg || 'Unknown error', mode },
- },
- }));
- } catch (e) {
- setOutboundTestStates((prev) => ({
- ...prev,
- [index]: {
- testing: false,
- result: { success: false, error: String(e), mode },
- },
- }));
- }
- return null;
- },
- [],
- );
- const testAllOutbounds = useCallback(async (mode = 'tcp') => {
- const list = templateSettingsRef.current?.outbounds || [];
- if (list.length === 0 || testingAll) return;
- setTestingAll(true);
- try {
- const concurrency = mode === 'tcp' ? 8 : 1;
- const queue = list
- .map((ob, i) => ({ index: i, outbound: ob }))
- .filter(({ outbound }) => {
- const tag = outbound?.tag;
- const proto = outbound?.protocol;
- if (proto === 'blackhole' || proto === 'loopback' || tag === 'blocked') return false;
- if (mode === 'tcp' && (proto === 'freedom' || proto === 'dns')) return false;
- return true;
- });
- async function worker() {
- while (queue.length > 0) {
- const item = queue.shift();
- if (!item) break;
- await testOutbound(item.index, item.outbound, mode);
- }
- }
- const workers = Array.from(
- { length: Math.min(concurrency, queue.length) },
- () => worker(),
- );
- await Promise.all(workers);
- } finally {
- setTestingAll(false);
- }
- }, [testingAll, testOutbound]);
- useEffect(() => {
- const timer = window.setInterval(() => {
- const dirtyXray = oldXraySettingRef.current !== xraySettingRef.current;
- const dirtyUrl = oldOutboundTestUrlRef.current !== outboundTestUrlRef.current;
- setSaveDisabled(!(dirtyXray || dirtyUrl));
- }, DIRTY_POLL_MS);
- return () => window.clearInterval(timer);
- }, []);
- const outboundsTraffic = useMemo(() => trafficQuery.data ?? [], [trafficQuery.data]);
- return useMemo(
- () => ({
- fetched,
- spinning,
- saveDisabled,
- fetchError,
- xraySetting,
- setXraySetting,
- templateSettings,
- setTemplateSettings,
- outboundTestUrl,
- setOutboundTestUrl,
- inboundTags,
- clientReverseTags,
- restartResult,
- outboundsTraffic,
- outboundTestStates,
- testingAll,
- fetchAll,
- fetchOutboundsTraffic: fetchOutboundsTrafficCb,
- resetOutboundsTraffic,
- testOutbound,
- testAllOutbounds,
- saveAll,
- resetToDefault,
- restartXray,
- }),
- [
- fetched,
- spinning,
- saveDisabled,
- fetchError,
- xraySetting,
- setXraySetting,
- templateSettings,
- setTemplateSettings,
- outboundTestUrl,
- setOutboundTestUrl,
- inboundTags,
- clientReverseTags,
- restartResult,
- outboundsTraffic,
- outboundTestStates,
- testingAll,
- fetchAll,
- fetchOutboundsTrafficCb,
- resetOutboundsTraffic,
- testOutbound,
- testAllOutbounds,
- saveAll,
- resetToDefault,
- restartXray,
- ],
- );
- }
|