ClientInfoModal.tsx 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  1. import { useEffect, useMemo, useState } from 'react';
  2. import { useTranslation } from 'react-i18next';
  3. import { Button, Divider, Modal, Popover, Tag, Tooltip, message } from 'antd';
  4. import { CopyOutlined, EyeOutlined, QrcodeOutlined, ReloadOutlined } from '@ant-design/icons';
  5. import { ClipboardManager, HttpUtil, IntlUtil, SizeFormatter } from '@/utils';
  6. import { useDatepicker } from '@/hooks/useDatepicker';
  7. import type { ClientRecord, InboundOption } from '@/hooks/useClients';
  8. import { isPostQuantumLink } from '@/lib/xray/inbound-link';
  9. import { QrPanel } from '@/pages/inbounds/qr';
  10. import './ClientInfoModal.css';
  11. const PROTOCOL_COLORS: Record<string, string> = {
  12. VLESS: 'blue',
  13. VMESS: 'geekblue',
  14. TROJAN: 'volcano',
  15. SS: 'magenta',
  16. HYSTERIA: 'cyan',
  17. HY2: 'green',
  18. };
  19. const INBOUND_PROTOCOL_COLORS: Record<string, string> = {
  20. vless: 'blue',
  21. vmess: 'geekblue',
  22. trojan: 'volcano',
  23. shadowsocks: 'magenta',
  24. hysteria: 'cyan',
  25. hysteria2: 'green',
  26. wireguard: 'gold',
  27. http: 'purple',
  28. mixed: 'lime',
  29. tunnel: 'orange',
  30. };
  31. const INBOUND_CHIP_LIMIT = 1;
  32. // 3x-ui's genRemark concatenates inbound remark + client email (and an
  33. // optional extra) using a configurable separator. The email half is
  34. // redundant in the row title — the modal already names the client by
  35. // email at the top — so trimEmail strips it back out for the row only.
  36. // The original remark is preserved for the QR (it's the QR's own name).
  37. function trimEmail(remark: string, email: string): string {
  38. if (!email) return remark;
  39. const e = email.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  40. return remark
  41. .replace(new RegExp(`[-_.\\s|]+${e}$`), '')
  42. .replace(new RegExp(`^${e}[-_.\\s|]+`), '')
  43. .trim();
  44. }
  45. // Decode a base64 string as UTF-8. atob() returns a binary string where
  46. // each char holds one raw byte (Latin-1 interpretation), which mangles
  47. // any multi-byte UTF-8 sequence in the payload — most commonly the
  48. // emoji decorations the panel embeds in remarks (📊, ⏳).
  49. function base64DecodeUtf8(b64: string): string {
  50. const binary = atob(b64);
  51. const bytes = new Uint8Array(binary.length);
  52. for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
  53. return new TextDecoder('utf-8').decode(bytes);
  54. }
  55. function parseLinkMeta(link: string): { protocol: string; remark: string } {
  56. const schemeMatch = /^([a-z0-9]+):\/\//i.exec(link);
  57. const scheme = schemeMatch?.[1]?.toLowerCase() ?? '';
  58. const protocolMap: Record<string, string> = {
  59. vless: 'VLESS',
  60. vmess: 'VMESS',
  61. trojan: 'TROJAN',
  62. ss: 'SS',
  63. hysteria: 'HYSTERIA',
  64. hysteria2: 'HY2',
  65. hy2: 'HY2',
  66. };
  67. const protocol = protocolMap[scheme] ?? scheme.toUpperCase() ?? 'LINK';
  68. let remark = '';
  69. if (scheme === 'vmess') {
  70. try {
  71. const body = link.slice('vmess://'.length).split('#')[0];
  72. const json = JSON.parse(base64DecodeUtf8(body)) as { ps?: unknown };
  73. if (typeof json?.ps === 'string') remark = json.ps;
  74. } catch { /* fall through to fragment parsing */ }
  75. }
  76. if (!remark) {
  77. const hashIdx = link.indexOf('#');
  78. if (hashIdx >= 0) {
  79. const raw = link.slice(hashIdx + 1);
  80. try { remark = decodeURIComponent(raw); }
  81. catch { remark = raw; }
  82. }
  83. }
  84. return { protocol, remark };
  85. }
  86. interface SubSettings {
  87. enable: boolean;
  88. subURI: string;
  89. subJsonURI: string;
  90. subJsonEnable: boolean;
  91. subClashURI: string;
  92. subClashEnable: boolean;
  93. }
  94. interface ClientInfoModalProps {
  95. open: boolean;
  96. client: ClientRecord | null;
  97. inboundsById: Record<number, InboundOption>;
  98. isOnline: boolean;
  99. subSettings?: SubSettings;
  100. onOpenChange: (open: boolean) => void;
  101. }
  102. interface ApiMsg<T = unknown> {
  103. success?: boolean;
  104. obj?: T;
  105. }
  106. const DEFAULT_SUB: SubSettings = {
  107. enable: false,
  108. subURI: '',
  109. subJsonURI: '',
  110. subJsonEnable: false,
  111. subClashURI: '',
  112. subClashEnable: false,
  113. };
  114. export default function ClientInfoModal({
  115. open,
  116. client,
  117. inboundsById,
  118. isOnline,
  119. subSettings = DEFAULT_SUB,
  120. onOpenChange,
  121. }: ClientInfoModalProps) {
  122. const { datepicker } = useDatepicker();
  123. const { t } = useTranslation();
  124. const expiryLabel = (ts?: number) => {
  125. if (!ts) return '∞';
  126. if (ts < 0) {
  127. const days = Math.round(ts / -86400000);
  128. return `${t('pages.clients.delayedStart')}: ${days}d`;
  129. }
  130. return IntlUtil.formatDate(ts, datepicker);
  131. };
  132. const dateLabel = (ts?: number) => (!ts || ts <= 0 ? '-' : IntlUtil.formatDate(ts, datepicker));
  133. const [messageApi, messageContextHolder] = message.useMessage();
  134. const [links, setLinks] = useState<string[]>([]);
  135. const [clientIps, setClientIps] = useState<string[]>([]);
  136. const [ipsLoading, setIpsLoading] = useState(false);
  137. const [ipsClearing, setIpsClearing] = useState(false);
  138. const [ipsModalOpen, setIpsModalOpen] = useState(false);
  139. useEffect(() => {
  140. if (!open) {
  141. setLinks([]);
  142. setClientIps([]);
  143. setIpsModalOpen(false);
  144. return;
  145. }
  146. if (!client?.subId) return;
  147. let cancelled = false;
  148. (async () => {
  149. const msg = await HttpUtil.get(
  150. `/panel/api/clients/subLinks/${encodeURIComponent(client.subId!)}`,
  151. ) as ApiMsg<string[]>;
  152. if (cancelled) return;
  153. setLinks(msg?.success && Array.isArray(msg.obj) ? msg.obj : []);
  154. })();
  155. return () => { cancelled = true; };
  156. }, [open, client?.subId]);
  157. const traffic = client?.traffic || null;
  158. const totalBytes = client?.totalGB || 0;
  159. const used = (traffic?.up || 0) + (traffic?.down || 0);
  160. const remaining = useMemo(() => {
  161. if (totalBytes <= 0) return -1;
  162. const r = totalBytes - used;
  163. return r > 0 ? r : 0;
  164. }, [totalBytes, used]);
  165. const subLink = useMemo(() => {
  166. if (!client?.subId || !subSettings?.subURI) return '';
  167. return subSettings.subURI + client.subId;
  168. }, [client?.subId, subSettings?.subURI]);
  169. const subJsonLink = useMemo(() => {
  170. if (!client?.subId) return '';
  171. if (!subSettings?.subJsonEnable || !subSettings?.subJsonURI) return '';
  172. return subSettings.subJsonURI + client.subId;
  173. }, [client?.subId, subSettings?.subJsonEnable, subSettings?.subJsonURI]);
  174. const subClashLink = useMemo(() => {
  175. if (!client?.subId) return '';
  176. if (!subSettings?.subClashEnable || !subSettings?.subClashURI) return '';
  177. return subSettings.subClashURI + client.subId;
  178. }, [client?.subId, subSettings?.subClashEnable, subSettings?.subClashURI]);
  179. const showSubscription = !!(subSettings?.enable && client?.subId);
  180. async function copyValue(text: string) {
  181. if (!text) return;
  182. const ok = await ClipboardManager.copyText(String(text));
  183. if (ok) messageApi.success(t('copied'));
  184. }
  185. async function loadIps() {
  186. if (!client?.email) return;
  187. setIpsLoading(true);
  188. try {
  189. const msg = await HttpUtil.post(`/panel/api/clients/ips/${encodeURIComponent(client.email)}`) as ApiMsg<unknown[]>;
  190. if (!msg?.success) { setClientIps([]); return; }
  191. const arr = Array.isArray(msg.obj) ? msg.obj : [];
  192. setClientIps(arr.filter((x): x is string => typeof x === 'string' && x.length > 0));
  193. } finally {
  194. setIpsLoading(false);
  195. }
  196. }
  197. async function clearIps() {
  198. if (!client?.email) return;
  199. setIpsClearing(true);
  200. try {
  201. const msg = await HttpUtil.post(`/panel/api/clients/clearIps/${encodeURIComponent(client.email)}`) as ApiMsg;
  202. if (msg?.success) setClientIps([]);
  203. } finally {
  204. setIpsClearing(false);
  205. }
  206. }
  207. function openIpsModal() {
  208. setIpsModalOpen(true);
  209. if (clientIps.length === 0) void loadIps();
  210. }
  211. return (
  212. <>
  213. {messageContextHolder}
  214. <Modal
  215. open={open}
  216. title={client ? `${t('pages.clients.clientInfo')} — ${client.email}` : t('pages.clients.clientInfo')}
  217. footer={null}
  218. width={640}
  219. onCancel={() => onOpenChange(false)}
  220. >
  221. {client && (
  222. <>
  223. <table className="info-table block">
  224. <tbody>
  225. <tr>
  226. <td>{t('pages.clients.online')}</td>
  227. <td>
  228. {client.enable && isOnline
  229. ? <Tag color="green">{t('pages.clients.online')}</Tag>
  230. : <Tag>{t('pages.clients.offline')}</Tag>}
  231. <span className="hint">{t('lastOnline')}: {dateLabel(traffic?.lastOnline)}</span>
  232. </td>
  233. </tr>
  234. <tr>
  235. <td>{t('status')}</td>
  236. <td>
  237. <Tag color={client.enable ? 'green' : 'default'}>
  238. {client.enable ? t('enabled') : t('disabled')}
  239. </Tag>
  240. </td>
  241. </tr>
  242. <tr>
  243. <td>{t('pages.clients.email')}</td>
  244. <td>
  245. {client.email
  246. ? <Tag color="green">{client.email}</Tag>
  247. : <Tag color="red">{t('none')}</Tag>}
  248. </td>
  249. </tr>
  250. <tr>
  251. <td>{t('pages.clients.subId')}</td>
  252. <td>
  253. <Tag className="info-large-tag">{client.subId || '-'}</Tag>
  254. {client.subId && (
  255. <Button size="small" type="text" icon={<CopyOutlined />} onClick={() => copyValue(client.subId!)} />
  256. )}
  257. </td>
  258. </tr>
  259. {client.uuid && (
  260. <tr>
  261. <td>{t('pages.clients.uuid')}</td>
  262. <td>
  263. <Tag className="info-large-tag">{client.uuid}</Tag>
  264. <Button size="small" type="text" icon={<CopyOutlined />} onClick={() => copyValue(client.uuid!)} />
  265. </td>
  266. </tr>
  267. )}
  268. {client.password && (
  269. <tr>
  270. <td>{t('password')}</td>
  271. <td>
  272. <Tag className="info-large-tag">{client.password}</Tag>
  273. <Button size="small" type="text" icon={<CopyOutlined />} onClick={() => copyValue(client.password!)} />
  274. </td>
  275. </tr>
  276. )}
  277. {client.auth && (
  278. <tr>
  279. <td>{t('pages.clients.auth')}</td>
  280. <td>
  281. <Tag className="info-large-tag">{client.auth}</Tag>
  282. <Button size="small" type="text" icon={<CopyOutlined />} onClick={() => copyValue(client.auth!)} />
  283. </td>
  284. </tr>
  285. )}
  286. <tr>
  287. <td>{t('pages.clients.flow')}</td>
  288. <td>
  289. {client.flow ? <Tag>{client.flow}</Tag> : <Tag color="orange">{t('none')}</Tag>}
  290. </td>
  291. </tr>
  292. <tr>
  293. <td>{t('pages.inbounds.traffic')}</td>
  294. <td>
  295. <Tag>
  296. ↑ {SizeFormatter.sizeFormat(traffic?.up || 0)}
  297. {' '}/ ↓ {SizeFormatter.sizeFormat(traffic?.down || 0)}
  298. </Tag>
  299. <span className="hint">
  300. {SizeFormatter.sizeFormat(used)} / {totalBytes > 0 ? SizeFormatter.sizeFormat(totalBytes) : '∞'}
  301. </span>
  302. </td>
  303. </tr>
  304. <tr>
  305. <td>{t('remained')}</td>
  306. <td>
  307. {remaining < 0
  308. ? <Tag color="purple">∞</Tag>
  309. : <Tag color={remaining > 0 ? '' : 'red'}>{SizeFormatter.sizeFormat(remaining)}</Tag>}
  310. </td>
  311. </tr>
  312. <tr>
  313. <td>{t('pages.inbounds.expireDate')}</td>
  314. <td>
  315. {!client.expiryTime
  316. ? <Tag color="purple">∞</Tag>
  317. : <Tag color={client.expiryTime < 0 ? 'blue' : undefined}>{expiryLabel(client.expiryTime)}</Tag>}
  318. {(client.expiryTime ?? 0) > 0 && (
  319. <span className="hint">{IntlUtil.formatRelativeTime(client.expiryTime)}</span>
  320. )}
  321. </td>
  322. </tr>
  323. <tr>
  324. <td>{t('pages.clients.ipLimit')}</td>
  325. <td>{!client.limitIp ? <Tag>∞</Tag> : <Tag>{client.limitIp}</Tag>}</td>
  326. </tr>
  327. <tr>
  328. <td>{t('pages.inbounds.IPLimitlog')}</td>
  329. <td>
  330. <Button size="small" icon={<EyeOutlined />} loading={ipsLoading} onClick={openIpsModal}>
  331. {clientIps.length > 0 ? clientIps.length : ''}
  332. </Button>
  333. </td>
  334. </tr>
  335. <tr>
  336. <td>{t('pages.inbounds.createdAt')}</td>
  337. <td><Tag>{dateLabel(client.createdAt)}</Tag></td>
  338. </tr>
  339. <tr>
  340. <td>{t('pages.inbounds.updatedAt')}</td>
  341. <td><Tag>{dateLabel(client.updatedAt)}</Tag></td>
  342. </tr>
  343. {client.comment && (
  344. <tr>
  345. <td>{t('pages.clients.comment')}</td>
  346. <td><Tag className="info-large-tag">{client.comment}</Tag></td>
  347. </tr>
  348. )}
  349. <tr>
  350. <td>{t('pages.clients.attachedInbounds')}</td>
  351. <td>
  352. {(() => {
  353. const ids = client.inboundIds || [];
  354. if (ids.length === 0) return <span className="hint">—</span>;
  355. const visible = ids.slice(0, INBOUND_CHIP_LIMIT);
  356. const overflow = ids.slice(INBOUND_CHIP_LIMIT);
  357. const inboundChip = (id: number) => {
  358. const ib = inboundsById[id];
  359. const proto = (ib?.protocol || '').toLowerCase();
  360. const color = INBOUND_PROTOCOL_COLORS[proto] ?? 'default';
  361. const label = ib?.tag ?? '';
  362. return (
  363. <Tooltip key={id} title={label}>
  364. <Tag color={color}>{label}</Tag>
  365. </Tooltip>
  366. );
  367. };
  368. return (
  369. <div className="chips">
  370. {visible.map((id) => inboundChip(id))}
  371. {overflow.length > 0 && (
  372. <Popover
  373. trigger="click"
  374. placement="bottomRight"
  375. content={
  376. <div className="chips chips-stack">
  377. {overflow.map((id) => inboundChip(id))}
  378. </div>
  379. }
  380. >
  381. <Tag color="default" className="chip-more">
  382. +{overflow.length} {t('more') !== 'more' ? t('more') : 'more'}
  383. </Tag>
  384. </Popover>
  385. )}
  386. </div>
  387. );
  388. })()}
  389. </td>
  390. </tr>
  391. </tbody>
  392. </table>
  393. {links.length > 0 && (
  394. <>
  395. <Divider>{t('pages.inbounds.copyLink')}</Divider>
  396. {links.map((link, idx) => {
  397. const meta = parseLinkMeta(link);
  398. const rowTitle = trimEmail(meta.remark, client.email)
  399. || `${t('pages.clients.link')} ${idx + 1}`;
  400. const qrRemark = client.email
  401. ? `${rowTitle}-${client.email}`
  402. : (meta.remark || `${t('pages.clients.link')} ${idx + 1}`);
  403. const canQr = !isPostQuantumLink(link);
  404. return (
  405. <div key={idx} className="link-row">
  406. <Tag color={PROTOCOL_COLORS[meta.protocol] ?? 'default'} className="link-row-tag">
  407. {meta.protocol}
  408. </Tag>
  409. <span className="link-row-title" title={qrRemark}>{rowTitle}</span>
  410. <div className="link-row-actions">
  411. <Tooltip title={t('copy')}>
  412. <Button size="small" icon={<CopyOutlined />} onClick={() => copyValue(link)} />
  413. </Tooltip>
  414. {canQr && (
  415. <Popover
  416. trigger="click"
  417. placement="left"
  418. destroyOnHidden
  419. content={<QrPanel value={link} remark={qrRemark} size={220} />}
  420. >
  421. <Tooltip title={t('pages.clients.qrCode')}>
  422. <Button size="small" icon={<QrcodeOutlined />} />
  423. </Tooltip>
  424. </Popover>
  425. )}
  426. </div>
  427. </div>
  428. );
  429. })}
  430. </>
  431. )}
  432. {showSubscription && subLink && (
  433. <>
  434. <Divider>{t('subscription.title')}</Divider>
  435. <div className="link-row">
  436. <Tag color="green" className="link-row-tag">SUB</Tag>
  437. <a
  438. href={subLink}
  439. target="_blank"
  440. rel="noopener noreferrer"
  441. className="link-row-title link-row-title-anchor"
  442. title={subLink}
  443. >
  444. {client.subId}
  445. </a>
  446. <div className="link-row-actions">
  447. <Tooltip title={t('copy')}>
  448. <Button size="small" icon={<CopyOutlined />} onClick={() => copyValue(subLink)} />
  449. </Tooltip>
  450. <Popover
  451. trigger="click"
  452. placement="left"
  453. destroyOnHidden
  454. content={<QrPanel value={subLink} remark={`${client.email} — ${t('subscription.title')}`} size={220} />}
  455. >
  456. <Tooltip title={t('pages.clients.qrCode')}>
  457. <Button size="small" icon={<QrcodeOutlined />} />
  458. </Tooltip>
  459. </Popover>
  460. </div>
  461. </div>
  462. {subJsonLink && (
  463. <div className="link-row">
  464. <Tag color="purple" className="link-row-tag">JSON</Tag>
  465. <a
  466. href={subJsonLink}
  467. target="_blank"
  468. rel="noopener noreferrer"
  469. className="link-row-title link-row-title-anchor"
  470. title={subJsonLink}
  471. >
  472. {client.subId}
  473. </a>
  474. <div className="link-row-actions">
  475. <Tooltip title={t('copy')}>
  476. <Button size="small" icon={<CopyOutlined />} onClick={() => copyValue(subJsonLink)} />
  477. </Tooltip>
  478. <Popover
  479. trigger="click"
  480. placement="left"
  481. destroyOnHidden
  482. content={<QrPanel value={subJsonLink} remark={`${client.email} — JSON`} size={220} />}
  483. >
  484. <Tooltip title={t('pages.clients.qrCode')}>
  485. <Button size="small" icon={<QrcodeOutlined />} />
  486. </Tooltip>
  487. </Popover>
  488. </div>
  489. </div>
  490. )}
  491. {subClashLink && (
  492. <div className="link-row">
  493. <Tooltip title="Clash / Mihomo">
  494. <Tag color="gold" className="link-row-tag">CLASH</Tag>
  495. </Tooltip>
  496. <a
  497. href={subClashLink}
  498. target="_blank"
  499. rel="noopener noreferrer"
  500. className="link-row-title link-row-title-anchor"
  501. title={subClashLink}
  502. >
  503. {client.subId}
  504. </a>
  505. <div className="link-row-actions">
  506. <Tooltip title={t('copy')}>
  507. <Button size="small" icon={<CopyOutlined />} onClick={() => copyValue(subClashLink)} />
  508. </Tooltip>
  509. <Popover
  510. trigger="click"
  511. placement="left"
  512. destroyOnHidden
  513. content={<QrPanel value={subClashLink} remark={`${client.email} — Clash / Mihomo`} size={220} />}
  514. >
  515. <Tooltip title={t('pages.clients.qrCode')}>
  516. <Button size="small" icon={<QrcodeOutlined />} />
  517. </Tooltip>
  518. </Popover>
  519. </div>
  520. </div>
  521. )}
  522. </>
  523. )}
  524. </>
  525. )}
  526. </Modal>
  527. <Modal
  528. open={ipsModalOpen}
  529. title={`${t('pages.inbounds.IPLimitlog')}${client?.email ? ` — ${client.email}` : ''}`}
  530. width={440}
  531. onCancel={() => setIpsModalOpen(false)}
  532. footer={[
  533. <Button key="refresh" icon={<ReloadOutlined />} loading={ipsLoading} onClick={loadIps}>
  534. {t('refresh')}
  535. </Button>,
  536. <Button key="clear" danger loading={ipsClearing} disabled={clientIps.length === 0} onClick={clearIps}>
  537. {t('pages.clients.clearAll')}
  538. </Button>,
  539. <Button key="close" type="primary" onClick={() => setIpsModalOpen(false)}>
  540. {t('close')}
  541. </Button>,
  542. ]}
  543. >
  544. {clientIps.length > 0 ? (
  545. <div style={{ maxHeight: 360, overflowY: 'auto' }}>
  546. {clientIps.map((ip, idx) => (
  547. <Tag
  548. key={idx}
  549. color="blue"
  550. style={{
  551. display: 'block',
  552. width: 'fit-content',
  553. maxWidth: '100%',
  554. marginBottom: 6,
  555. padding: '2px 8px',
  556. fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace',
  557. }}
  558. >
  559. {ip}
  560. </Tag>
  561. ))}
  562. </div>
  563. ) : (
  564. <Tag>{t('tgbot.noIpRecord')}</Tag>
  565. )}
  566. </Modal>
  567. </>
  568. );
  569. }