}
- disabled={rows.length === 0}
- onClick={() =>
- copy(allText, t('pages.clients.subLinksCopiedAll', { count: rows.length }))
- }
+ disabled={!total}
+ loading={copying}
+ onClick={copyAll}
>
{t('pages.clients.subLinksCopyAll')}
}
- disabled={rows.length === 0}
- onClick={download}
+ disabled={!total}
+ href={exportPath}
+ download={exportPath ? 'sub-links.txt' : undefined}
+ onClick={exportPath ? undefined : download}
>
{t('download')}
@@ -187,7 +236,7 @@ export default function SubLinksModal({
style={{ marginBottom: 12 }}
/>
)}
- {enabled && rows.length === 0 && (
+ {enabled && !total && !groupPage.isFetching && !groupPage.isError && (
)}
- {rows.length > 0 && (
+ {groupPage.isError && (
+
+ )}
+ {enabled && (total > 0 || groupPage.isFetching) && (
dataSource={rows}
columns={columns}
size="small"
- pagination={false}
+ loading={groupPage.isFetching}
+ pagination={
+ group
+ ? {
+ current: page,
+ pageSize: GROUP_CLIENT_PAGE_SIZE,
+ total,
+ showSizeChanger: false,
+ onChange: setPage,
+ }
+ : false
+ }
scroll={{ y: 360 }}
/>
)}
diff --git a/frontend/src/pages/groups/GroupAddClientsModal.tsx b/frontend/src/pages/groups/GroupAddClientsModal.tsx
deleted file mode 100644
index 5655cd38a..000000000
--- a/frontend/src/pages/groups/GroupAddClientsModal.tsx
+++ /dev/null
@@ -1,171 +0,0 @@
-import { useMemo, useState } from 'react';
-import { useTranslation } from 'react-i18next';
-import { Alert, Input, Modal, Space, Table, Tag, Typography, message } from 'antd';
-import type { ColumnsType } from 'antd/es/table';
-
-import type { ClientRecord } from '@/hooks/useClients';
-
-interface GroupAddClientsModalProps {
- open: boolean;
- groupName: string | null;
- candidates: ClientRecord[];
- onClose: () => void;
- onSubmit: (emails: string[]) => Promise<{ affected?: number } | null>;
-}
-
-interface ClientRow {
- email: string;
- comment: string;
- enable: boolean;
- currentGroup: string;
-}
-
-export default function GroupAddClientsModal({
- open,
- groupName,
- candidates,
- onClose,
- onSubmit,
-}: GroupAddClientsModalProps) {
- const { t } = useTranslation();
- const [messageApi, messageContextHolder] = message.useMessage();
- const [saving, setSaving] = useState(false);
- const [selectedEmails, setSelectedEmails] = useState([]);
- const [search, setSearch] = useState('');
-
- const rows = useMemo(
- () =>
- (candidates || [])
- .map((c) => ({
- email: (c.email || '').trim(),
- comment: (c.comment || '').trim(),
- enable: c.enable !== false,
- currentGroup: (c.group || '').trim(),
- }))
- .filter((r) => r.email),
- [candidates],
- );
-
- // React resets this during render rather than in an effect so the modal's
- // first open frame already shows cleared fields.
- const [wasOpen, setWasOpen] = useState(false);
- if (open !== wasOpen) {
- setWasOpen(open);
- if (open) {
- setSelectedEmails([]);
- setSearch('');
- }
- }
-
- const filteredRows = useMemo(() => {
- const q = search.trim().toLowerCase();
- if (!q) return rows;
- return rows.filter(
- (r) =>
- r.email.toLowerCase().includes(q) ||
- r.comment.toLowerCase().includes(q) ||
- r.currentGroup.toLowerCase().includes(q),
- );
- }, [rows, search]);
-
- const columns: ColumnsType = useMemo(
- () => [
- { title: t('pages.inbounds.email'), dataIndex: 'email', key: 'email', ellipsis: true },
- { title: t('comment'), dataIndex: 'comment', key: 'comment', ellipsis: true },
- {
- title: t('pages.clients.group'),
- dataIndex: 'currentGroup',
- key: 'currentGroup',
- width: 140,
- ellipsis: true,
- render: (g: string) =>
- g ? (
- {g}
- ) : (
- —
- ),
- },
- {
- title: t('enable'),
- dataIndex: 'enable',
- key: 'enable',
- width: 90,
- render: (enabled: boolean) =>
- enabled ? (
- {t('enable')}
- ) : (
- {t('pages.inbounds.attachClientsStatusDisabled')}
- ),
- },
- ],
- [t],
- );
-
- async function submit() {
- if (!groupName || selectedEmails.length === 0) return;
- setSaving(true);
- try {
- const result = await onSubmit(selectedEmails);
- if (!result) return;
- const affected = result.affected ?? selectedEmails.length;
- messageApi.success(t('pages.groups.addToGroupResult', { count: affected, name: groupName }));
- onClose();
- } finally {
- setSaving(false);
- }
- }
-
- return (
-
- {messageContextHolder}
-
- {t('pages.groups.addToGroupDesc')}
-
-
-
-
- setSearch(e.target.value)}
- placeholder={t('pages.inbounds.attachClientsSearchPlaceholder')}
- aria-label={t('pages.inbounds.attachClientsSearchPlaceholder')}
- style={{ maxWidth: 320 }}
- />
-
- {t('pages.inbounds.attachClientsSelectedCount', {
- selected: selectedEmails.length,
- total: rows.length,
- })}
-
-
- {rows.length === 0 ? (
-
- ) : (
-
- size="small"
- rowKey="email"
- columns={columns}
- dataSource={filteredRows}
- pagination={false}
- scroll={{ y: 320 }}
- rowSelection={{
- selectedRowKeys: selectedEmails,
- onChange: (keys) => setSelectedEmails(keys as string[]),
- preserveSelectedRowKeys: true,
- }}
- />
- )}
-
-
- );
-}
diff --git a/frontend/src/pages/groups/GroupClientsModal.tsx b/frontend/src/pages/groups/GroupClientsModal.tsx
new file mode 100644
index 000000000..3fcf59aa4
--- /dev/null
+++ b/frontend/src/pages/groups/GroupClientsModal.tsx
@@ -0,0 +1,283 @@
+import { useEffect, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Alert, Button, Input, Modal, Space, Table, Tag, Typography, message } from 'antd';
+import type { ColumnsType } from 'antd/es/table';
+
+import {
+ GROUP_CLIENT_PAGE_SIZE,
+ MAX_GROUP_EXCLUSIONS,
+ fetchGroupClients,
+ useGroupClientPage,
+ type GroupClientSelection,
+} from '@/api/groupClients';
+import type { GroupClientRow } from '@/generated/zod';
+
+interface GroupClientsModalProps {
+ group: string;
+ mode: 'add' | 'remove';
+ onClose: () => void;
+ onSubmit: (selection: GroupClientSelection) => Promise<{ affected?: number } | null>;
+}
+
+export default function GroupClientsModal({
+ group,
+ mode,
+ onClose,
+ onSubmit,
+}: GroupClientsModalProps) {
+ const { t } = useTranslation();
+ const [messages, holder] = message.useMessage();
+ const [page, setPage] = useState(1);
+ const [search, setSearch] = useState('');
+ const [debouncedSearch, setDebouncedSearch] = useState('');
+ const [choices, setChoices] = useState(new Set());
+ const [frozen, setFrozen] = useState<{
+ token: string;
+ count: number;
+ maxId: number;
+ search: string;
+ }>();
+ const [busy, setBusy] = useState<'freeze' | 'submit'>();
+ const action = useRef(false);
+
+ useEffect(() => {
+ const timer = window.setTimeout(() => setDebouncedSearch(search), 220);
+ return () => window.clearTimeout(timer);
+ }, [search]);
+
+ const query = useGroupClientPage(
+ {
+ group,
+ mode,
+ page,
+ search: debouncedSearch,
+ maxId: frozen?.maxId,
+ scopeSearch: frozen?.search,
+ },
+ search === debouncedSearch,
+ );
+ const loading = search !== debouncedSearch || query.isFetching;
+ const rows = loading ? [] : (query.data?.items ?? []);
+ const selected = frozen ? frozen.count - choices.size : choices.size;
+ const visible = rows.filter((row) => !frozen || row.inScope);
+ const add = mode === 'add';
+
+ function clearSelection() {
+ setFrozen(undefined);
+ setChoices(new Set());
+ }
+
+ function selectVisible(keys: React.Key[]) {
+ const checked = new Set(keys);
+ const next = new Set(choices);
+ for (const row of visible) {
+ if (frozen ? !checked.has(row.id) : checked.has(row.id)) next.add(row.id);
+ else next.delete(row.id);
+ }
+ if (next.size > (frozen ? MAX_GROUP_EXCLUSIONS : 50_000)) {
+ messages.warning(
+ t('pages.groups.selectionLimit', { count: frozen ? MAX_GROUP_EXCLUSIONS : 50_000 }),
+ );
+ return;
+ }
+ setChoices(next);
+ }
+
+ async function selectAll() {
+ if (action.current || loading) return;
+ action.current = true;
+ setBusy('freeze');
+ try {
+ const result = await fetchGroupClients({
+ group,
+ mode,
+ search: debouncedSearch,
+ freeze: true,
+ });
+ if (!result.scopeToken || !result.maxId || !result.total) {
+ clearSelection();
+ return;
+ }
+ setChoices(new Set());
+ setFrozen({
+ token: result.scopeToken,
+ maxId: result.maxId,
+ count: result.total,
+ search: debouncedSearch,
+ });
+ } catch (error) {
+ messages.error((error instanceof Error && error.message) || t('somethingWentWrong'));
+ } finally {
+ action.current = false;
+ setBusy(undefined);
+ }
+ }
+
+ async function submit() {
+ if (action.current || selected <= 0) return;
+ action.current = true;
+ setBusy('submit');
+ try {
+ const selection: GroupClientSelection = frozen
+ ? {
+ mode: 'allMatching',
+ scopeToken: frozen.token,
+ search: frozen.search,
+ excludedClientIds: [...choices],
+ }
+ : { mode: 'explicit', clientIds: [...choices] };
+ const result = await onSubmit(selection);
+ if (result) {
+ messages.success(
+ t(add ? 'pages.groups.addToGroupResult' : 'pages.groups.removeFromGroupResult', {
+ count: result.affected ?? 0,
+ name: group,
+ }),
+ );
+ onClose();
+ }
+ } finally {
+ action.current = false;
+ setBusy(undefined);
+ }
+ }
+
+ const columns: ColumnsType = [
+ { title: t('pages.inbounds.email'), dataIndex: 'email', width: 220, ellipsis: true },
+ { title: t('comment'), dataIndex: 'comment', ellipsis: true },
+ ...(add
+ ? [
+ {
+ title: t('pages.clients.group'),
+ dataIndex: 'group',
+ width: 140,
+ ellipsis: true,
+ render: (label: string) => (label ? {label} : '—'),
+ },
+ ]
+ : []),
+ {
+ title: t('enable'),
+ dataIndex: 'enable',
+ width: 100,
+ render: (enabled: boolean) => (
+
+ {t(enabled ? 'enable' : 'pages.inbounds.attachClientsStatusDisabled')}
+
+ ),
+ },
+ ];
+
+ return (
+ {
+ if (!action.current) onClose();
+ }}
+ onOk={submit}
+ okButtonProps={{ disabled: selected <= 0 || !!busy, danger: !add }}
+ confirmLoading={busy === 'submit'}
+ okText={t(add ? 'add' : 'remove')}
+ cancelText={t('cancel')}
+ cancelButtonProps={{ disabled: !!busy }}
+ title={t(add ? 'pages.groups.addToGroupTitle' : 'pages.groups.removeFromGroupTitle', {
+ name: group,
+ })}
+ width={720}
+ >
+ {holder}
+
+ {t(add ? 'pages.groups.addToGroupDesc' : 'pages.groups.removeFromGroupDesc')}
+
+
+ {
+ setSearch(event.target.value);
+ setPage(1);
+ }}
+ maxLength={256}
+ placeholder={t('pages.inbounds.attachClientsSearchPlaceholder')}
+ aria-label={t('pages.inbounds.attachClientsSearchPlaceholder')}
+ style={{ maxWidth: 320 }}
+ />
+
+
+
+
+ {frozen && choices.size > 0 && (
+
+ )}
+
+ {t('pages.inbounds.attachClientsSelectedCount', {
+ selected,
+ total: frozen?.count ?? query.data?.total ?? 0,
+ })}
+
+
+ {query.isError && (
+
+ )}
+ {!loading && !query.isError && !search && query.data?.total === 0 && (
+
+ )}
+
+ size="small"
+ rowKey="id"
+ virtual
+ columns={columns}
+ dataSource={rows}
+ loading={loading}
+ scroll={{ x: 620, y: 320 }}
+ pagination={{
+ current: page,
+ pageSize: GROUP_CLIENT_PAGE_SIZE,
+ total: query.data?.total ?? 0,
+ showSizeChanger: false,
+ disabled: !!busy,
+ onChange: setPage,
+ }}
+ rowSelection={{
+ selectedRowKeys: visible
+ .filter((row) => choices.has(row.id) !== !!frozen)
+ .map((row) => row.id),
+ onChange: selectVisible,
+ getTitleCheckboxProps: () => ({ 'aria-label': t('pages.inbounds.attachSelectPage') }),
+ getCheckboxProps: (row) => ({
+ 'aria-label': row.email,
+ disabled: !!busy || (!!frozen && !row.inScope),
+ }),
+ }}
+ />
+
+
+ );
+}
diff --git a/frontend/src/pages/groups/GroupRemoveClientsModal.tsx b/frontend/src/pages/groups/GroupRemoveClientsModal.tsx
deleted file mode 100644
index c462c8a49..000000000
--- a/frontend/src/pages/groups/GroupRemoveClientsModal.tsx
+++ /dev/null
@@ -1,151 +0,0 @@
-import { useMemo, useState } from 'react';
-import { useTranslation } from 'react-i18next';
-import { Input, Modal, Space, Table, Tag, Typography, message } from 'antd';
-import type { ColumnsType } from 'antd/es/table';
-
-import type { ClientRecord } from '@/hooks/useClients';
-
-interface GroupRemoveClientsModalProps {
- open: boolean;
- groupName: string | null;
- members: ClientRecord[];
- onClose: () => void;
- onSubmit: (emails: string[]) => Promise<{ affected?: number } | null>;
-}
-
-interface ClientRow {
- email: string;
- comment: string;
- enable: boolean;
-}
-
-export default function GroupRemoveClientsModal({
- open,
- groupName,
- members,
- onClose,
- onSubmit,
-}: GroupRemoveClientsModalProps) {
- const { t } = useTranslation();
- const [messageApi, messageContextHolder] = message.useMessage();
- const [saving, setSaving] = useState(false);
- const [selectedEmails, setSelectedEmails] = useState([]);
- const [search, setSearch] = useState('');
-
- const rows = useMemo(
- () =>
- (members || [])
- .map((c) => ({
- email: (c.email || '').trim(),
- comment: (c.comment || '').trim(),
- enable: c.enable !== false,
- }))
- .filter((r) => r.email),
- [members],
- );
-
- // React resets this during render rather than in an effect so the modal's
- // first open frame already shows cleared fields.
- const [wasOpen, setWasOpen] = useState(false);
- if (open !== wasOpen) {
- setWasOpen(open);
- if (open) {
- setSelectedEmails([]);
- setSearch('');
- }
- }
-
- const filteredRows = useMemo(() => {
- const q = search.trim().toLowerCase();
- if (!q) return rows;
- return rows.filter(
- (r) => r.email.toLowerCase().includes(q) || r.comment.toLowerCase().includes(q),
- );
- }, [rows, search]);
-
- const columns: ColumnsType = useMemo(
- () => [
- { title: t('pages.inbounds.email'), dataIndex: 'email', key: 'email', ellipsis: true },
- { title: t('comment'), dataIndex: 'comment', key: 'comment', ellipsis: true },
- {
- title: t('enable'),
- dataIndex: 'enable',
- key: 'enable',
- width: 90,
- render: (enabled: boolean) =>
- enabled ? (
- {t('enable')}
- ) : (
- {t('pages.inbounds.attachClientsStatusDisabled')}
- ),
- },
- ],
- [t],
- );
-
- async function submit() {
- if (!groupName || selectedEmails.length === 0) return;
- setSaving(true);
- try {
- const result = await onSubmit(selectedEmails);
- if (!result) return;
- const affected = result.affected ?? selectedEmails.length;
- messageApi.success(
- t('pages.groups.removeFromGroupResult', { count: affected, name: groupName }),
- );
- onClose();
- } finally {
- setSaving(false);
- }
- }
-
- return (
-
- {messageContextHolder}
-
- {t('pages.groups.removeFromGroupDesc')}
-
-
-
-
- setSearch(e.target.value)}
- placeholder={t('pages.inbounds.attachClientsSearchPlaceholder')}
- aria-label={t('pages.inbounds.attachClientsSearchPlaceholder')}
- style={{ maxWidth: 320 }}
- />
-
- {t('pages.inbounds.attachClientsSelectedCount', {
- selected: selectedEmails.length,
- total: rows.length,
- })}
-
-
-
- size="small"
- rowKey="email"
- columns={columns}
- dataSource={filteredRows}
- pagination={false}
- scroll={{ y: 280 }}
- rowSelection={{
- selectedRowKeys: selectedEmails,
- onChange: (keys) => setSelectedEmails(keys as string[]),
- preserveSelectedRowKeys: true,
- }}
- />
-
-
- );
-}
diff --git a/frontend/src/pages/groups/GroupsPage.stories.tsx b/frontend/src/pages/groups/GroupsPage.stories.tsx
new file mode 100644
index 000000000..4aad951a6
--- /dev/null
+++ b/frontend/src/pages/groups/GroupsPage.stories.tsx
@@ -0,0 +1,245 @@
+import { useState } from 'react';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import type { Meta, StoryObj } from '@storybook/react-vite';
+import { expect, waitFor, within } from 'storybook/test';
+import { Button } from 'antd';
+import { MemoryRouter } from 'react-router';
+
+import { ThemeProvider } from '@/hooks/useTheme';
+import AddClientsToGroupModal from '@/pages/inbounds/clients/AddClientsToGroupModal';
+import GroupsPage from './GroupsPage';
+
+const api = '/panel/api/clients';
+const group = 'staff';
+const groupCount = 10_000;
+const requests: { path: string; query: URLSearchParams; body?: Record }[] = [];
+const exportedLinks = Array.from({ length: groupCount }, (_, index) => {
+ const id = index + 1;
+ return `client-${id}@example.test\thttps://sub.example.test/plain/s${id}`;
+}).join('\n');
+let copiedLinks = '';
+
+function GroupFixture() {
+ const [queryClient] = useState(() => new QueryClient());
+ const [inboundOpen, setInboundOpen] = useState(false);
+ return (
+
+
+
+
+
+ setInboundOpen(false)}
+ />
+
+
+
+ );
+}
+
+function response(obj: unknown) {
+ return Promise.resolve(Response.json({ success: true, msg: '', obj }));
+}
+
+const meta = {
+ title: 'Pages/Groups/Client management',
+ component: GroupsPage,
+ render: () => ,
+} satisfies Meta;
+
+export default meta;
+type Story = StoryObj;
+
+export const LargeGroup: Story = {
+ parameters: { a11y: { context: '.ant-modal' } },
+ beforeEach: () => {
+ requests.length = 0;
+ copiedLinks = '';
+ const original = window.fetch;
+ const clipboard = Object.getOwnPropertyDescriptor(navigator, 'clipboard');
+ Object.defineProperty(navigator, 'clipboard', {
+ configurable: true,
+ value: {
+ writeText: async (value: string) => {
+ copiedLinks = value;
+ },
+ write: async (items: ClipboardItem[]) => {
+ copiedLinks = await (await items[0]!.getType('text/plain')).text();
+ },
+ },
+ });
+ window.fetch = (input, init) => {
+ const url = new URL(input instanceof Request ? input.url : input, window.location.href);
+ const path = url.pathname;
+ const query = url.searchParams;
+ const body =
+ typeof init?.body === 'string' && init.body.startsWith('{')
+ ? (JSON.parse(init.body) as Record)
+ : undefined;
+ requests.push({ path, query, body });
+ if (path === api + '/groups') {
+ return response([
+ {
+ id: 1,
+ name: group,
+ clientCount: groupCount,
+ hostGroupIds: [],
+ trafficUsed: 0,
+ up: 0,
+ down: 0,
+ },
+ ]);
+ }
+ if (path === '/panel/api/setting/defaultSettings') {
+ return response({ subEnable: true, subURI: 'https://sub.example.test/plain/' });
+ }
+ if (path === '/panel/api/setting/all') return response({});
+ if (path === '/csrf-token') return response('story-token');
+ if (path === api + '/groups/clientPage') {
+ const mode = query.get('mode');
+ const search = query.get('search');
+ const total = search ? 1 : mode === 'add' ? 40_000 : groupCount;
+ const maxId = mode === 'add' ? 50_000 : 10_000;
+ if (query.get('freeze') === 'true') {
+ return response({ items: [], total, scopeToken: `scope-${mode}-${search ?? ''}`, maxId });
+ }
+ const offset = (Number(query.get('page') ?? '1') - 1) * 100;
+ const items = Array.from({ length: Math.min(100, total) }, (_, index) => {
+ const id = search ? 10101 : (mode === 'add' ? groupCount : 0) + offset + index + 1;
+ return {
+ id,
+ email: `client-${id}@example.test`,
+ comment: '',
+ group: mode === 'add' ? '' : group,
+ enable: true,
+ subId: `s${id}`,
+ inScope: !query.get('scopeSearch') || id === 10101,
+ };
+ });
+ return response({ items, total });
+ }
+ if (path === api + '/groups/subLinks/export') {
+ return Promise.resolve(
+ new Response(exportedLinks, { headers: { 'Content-Type': 'text/plain' } }),
+ );
+ }
+ if (path === api + '/bulkAdjust') return response({ adjusted: groupCount });
+ if (path === api + '/bulkDel') return response({ deleted: groupCount });
+ if (path.endsWith('/bulkAdd') || path.endsWith('/bulkRemove'))
+ return response({ affected: 1 });
+ if (path.startsWith('/panel/api/')) return response([]);
+ return original(input, init);
+ };
+ return () => {
+ window.fetch = original;
+ if (clipboard) Object.defineProperty(navigator, 'clipboard', clipboard);
+ else Reflect.deleteProperty(navigator, 'clipboard');
+ };
+ },
+ play: async ({ userEvent }) => {
+ const screen = within(document.body);
+ const open = async (label: RegExp) => {
+ await userEvent.click((await screen.findAllByRole('button', { name: 'more' }))[0]!);
+ await userEvent.click(await screen.findByRole('menuitem', { name: label }));
+ return within(await screen.findByRole('dialog'));
+ };
+ const close = async (dialog: ReturnType, name = 'Cancel') => {
+ await userEvent.click(dialog.getAllByRole('button', { name }).at(-1)!);
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
+ };
+ const add = await open(/add clients…/i);
+ await add.findByText('client-10001@example.test');
+ await expect(add.getAllByRole('checkbox').length).toBeLessThan(101);
+ await userEvent.click(add.getByRole('button', { name: 'Select this page' }));
+ const nextPage = screen.getByRole('dialog').querySelector('.ant-pagination-next button');
+ if (!(nextPage instanceof HTMLButtonElement)) {
+ throw new Error(
+ 'Next page control missing: ' +
+ screen.getByRole('dialog').querySelector('.ant-pagination')?.outerHTML,
+ );
+ }
+ await userEvent.click(nextPage);
+ await waitFor(() => {
+ const loaded = requests
+ .filter((request) => request.path.endsWith('/clientPage'))
+ .map((request) => request.query.toString());
+ expect(loaded).toContain('group=staff&mode=add&page=2&search=');
+ });
+ await add.findByText('client-10101@example.test');
+ await expect(add.getByRole('status')).toHaveTextContent('100 of 40000 selected');
+ const selectAll = add.getByRole('button', { name: /Select all matching clients/i });
+ await userEvent.click(selectAll);
+ await waitFor(() => expect(selectAll).toHaveAttribute('aria-pressed', 'true'));
+ const checkbox = await add.findByRole('checkbox', { name: 'client-10101@example.test' });
+ await waitFor(() => expect(checkbox).toBeChecked());
+ await userEvent.click(checkbox);
+ await userEvent.type(add.getByRole('searchbox'), '10101');
+ await waitFor(() => expect(requests.some((r) => r.query.get('search') === '10101')).toBe(true));
+ await userEvent.click(add.getByRole('button', { name: /^Add$/ }));
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
+ await expect(requests.find((r) => r.path === api + '/groups/bulkAdd')?.body).toEqual({
+ group,
+ selection: {
+ mode: 'allMatching',
+ scopeToken: 'scope-add-',
+ search: '',
+ excludedClientIds: [10101],
+ },
+ });
+
+ const remove = await open(/remove clients…/i);
+ await remove.findByText('client-1@example.test');
+ await expect(remove.getAllByRole('checkbox').length).toBeLessThan(101);
+ await close(remove);
+
+ const links = await open(/sub links/i);
+ await links.findByText('https://sub.example.test/plain/s1');
+ await expect(links.getAllByRole('row').length).toBeLessThanOrEqual(101);
+ await expect(links.getByRole('link', { name: 'Download' })).toHaveAttribute(
+ 'href',
+ api + '/groups/subLinks/export?group=staff',
+ );
+ await userEvent.click(links.getByRole('button', { name: /copy all/i }));
+ await waitFor(() => expect(copiedLinks).toBe(exportedLinks));
+ await close(links, 'Close');
+
+ const adjust = await open(/adjust/i);
+ await userEvent.type(adjust.getByLabelText('Add days'), '1');
+ await userEvent.click(adjust.getByRole('button', { name: 'Confirm' }));
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
+ await expect(requests.find((r) => r.path === api + '/bulkAdjust')?.body).toMatchObject({
+ group,
+ scopeToken: 'scope-remove-',
+ addDays: 1,
+ });
+ const del = await open(/delete clients in group/i);
+ await userEvent.click(del.getByRole('button', { name: /^Delete$/ }));
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
+ await expect(requests.find((r) => r.path === api + '/bulkDel')?.body).toEqual({
+ group,
+ scopeToken: 'scope-remove-',
+ keepTraffic: false,
+ });
+
+ await userEvent.click(screen.getByRole('button', { name: 'Group the source inbound' }));
+ const inbound = within(await screen.findByRole('dialog'));
+ await userEvent.type(inbound.getByRole('combobox'), group);
+ await userEvent.click(inbound.getByRole('button', { name: /^Add$/ }));
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
+ await expect(requests.filter((r) => r.path === api + '/groups/bulkAdd').at(-1)?.body).toEqual({
+ inboundId: 7,
+ group,
+ });
+ await expect(
+ requests.some(
+ (r) =>
+ r.path === api + '/list' || r.path.endsWith('/emails') || Array.isArray(r.body?.emails),
+ ),
+ ).toBe(false);
+ const picker = await open(/add clients…/i);
+ await picker.findByRole('checkbox', { name: 'client-10001@example.test' });
+ },
+};
diff --git a/frontend/src/pages/groups/GroupsPage.tsx b/frontend/src/pages/groups/GroupsPage.tsx
index 407785f70..eba2eb841 100644
--- a/frontend/src/pages/groups/GroupsPage.tsx
+++ b/frontend/src/pages/groups/GroupsPage.tsx
@@ -1,4 +1,4 @@
-import { lazy, useCallback, useEffect, useId, useMemo, useState } from 'react';
+import { lazy, useCallback, useEffect, useId, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
Button,
@@ -39,7 +39,6 @@ import {
UsergroupDeleteOutlined,
} from '@ant-design/icons';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
-import { z } from 'zod';
import { useTheme } from '@/hooks/useTheme';
import { useMediaQuery } from '@/hooks/useMediaQuery';
@@ -50,24 +49,14 @@ import { setMessageInstance } from '@/utils/messageBus';
import AppSidebar from '@/layouts/AppSidebar';
import { LazyMount } from '@/components/utility';
import { keys } from '@/api/queryKeys';
-import {
- ClientRecordSchema,
- GroupSummaryListSchema,
- type ClientRecord,
- type GroupSummary,
-} from '@/schemas/client';
+import { fetchGroupClients, type GroupBulkScope } from '@/api/groupClients';
+import { GroupSummaryListSchema, type GroupSummary } from '@/schemas/client';
import { parseMsg } from '@/utils/zodValidate';
import HostGroupSelect from './HostGroupSelect';
-const ClientRecordListSchema = z
- .array(ClientRecordSchema)
- .nullable()
- .transform((v) => v ?? []);
-
const SubLinksModal = lazy(() => import('../clients/SubLinksModal'));
const ClientBulkAdjustModal = lazy(() => import('../clients/ClientBulkAdjustModal'));
-const GroupAddClientsModal = lazy(() => import('./GroupAddClientsModal'));
-const GroupRemoveClientsModal = lazy(() => import('./GroupRemoveClientsModal'));
+const GroupClientsModal = lazy(() => import('./GroupClientsModal'));
const GroupHostRulesModal = lazy(() => import('./GroupHostRulesModal'));
const JSON_HEADERS = { headers: { 'Content-Type': 'application/json' } } as const;
@@ -85,16 +74,6 @@ async function fetchGroups(): Promise {
return validated.obj ?? [];
}
-async function fetchEmailsForGroup(name: string): Promise {
- const msg = await HttpUtil.get(
- `/panel/api/clients/groups/${encodeURIComponent(name)}/emails`,
- undefined,
- { silent: true },
- );
- if (!msg?.success || !Array.isArray(msg.obj)) return [];
- return msg.obj;
-}
-
export default function GroupsPage() {
usePageTitle();
const { t } = useTranslation();
@@ -184,22 +163,10 @@ export default function GroupsPage() {
const [adjustOpen, setAdjustOpen] = useState(false);
const [addClientsOpen, setAddClientsOpen] = useState(false);
const [removeClientsOpen, setRemoveClientsOpen] = useState(false);
- const [groupEmails, setGroupEmails] = useState([]);
+ const [adjustScope, setAdjustScope] = useState<(GroupBulkScope & { count: number }) | null>(null);
+ const scopeRequest = useRef(0);
const [groupForAction, setGroupForAction] = useState(null);
- const allClientsQuery = useQuery({
- queryKey: keys.clients.all(),
- queryFn: async () => {
- const msg = await HttpUtil.get('/panel/api/clients/list', undefined, { silent: true });
- if (!msg?.success) throw new Error(msg?.msg || 'Failed to load clients');
- const validated = parseMsg(msg, ClientRecordListSchema, 'clients/list');
- return validated.obj ?? [];
- },
- enabled: addClientsOpen || removeClientsOpen || subLinksOpen,
- staleTime: 30_000,
- });
- const allClients = allClientsQuery.data ?? [];
-
const totalGroups = groups.length;
const totalClients = useMemo(
() => groups.reduce((acc, g) => acc + (g.clientCount || 0), 0),
@@ -289,37 +256,47 @@ export default function GroupsPage() {
});
}
- async function openSubLinksFor(g: GroupSummary) {
+ function openSubLinksFor(g: GroupSummary) {
if (!g.clientCount) {
messageApi.info(t('pages.groups.emptyForAction'));
return;
}
- const emails = await fetchEmailsForGroup(g.name);
- if (emails.length === 0) {
- messageApi.info(t('pages.groups.emptyForAction'));
- return;
- }
+ scopeRequest.current++;
setGroupForAction(g);
- setGroupEmails(emails);
setSubLinksOpen(true);
}
- async function openAdjustFor(g: GroupSummary) {
+ async function freezeGroup(g: GroupSummary) {
if (!g.clientCount) {
messageApi.info(t('pages.groups.emptyForAction'));
- return;
+ return null;
}
- const emails = await fetchEmailsForGroup(g.name);
- if (emails.length === 0) {
- messageApi.info(t('pages.groups.emptyForAction'));
- return;
+ const request = ++scopeRequest.current;
+ try {
+ const result = await fetchGroupClients({ group: g.name, mode: 'remove', freeze: true });
+ if (scopeRequest.current !== request) return null;
+ if (!result.total || !result.scopeToken) {
+ messageApi.info(t('pages.groups.emptyForAction'));
+ return null;
+ }
+ return { group: g.name, count: result.total, scopeToken: result.scopeToken };
+ } catch (error) {
+ if (scopeRequest.current === request) {
+ messageApi.error((error instanceof Error && error.message) || t('somethingWentWrong'));
+ }
+ return null;
}
- setGroupForAction(g);
- setGroupEmails(emails);
+ }
+
+ async function openAdjustFor(g: GroupSummary) {
+ const scope = await freezeGroup(g);
+ if (!scope) return;
+ setAdjustScope(scope);
setAdjustOpen(true);
}
function openAddClientsFor(g: GroupSummary) {
+ scopeRequest.current++;
setGroupForAction(g);
setAddClientsOpen(true);
}
@@ -344,29 +321,26 @@ export default function GroupsPage() {
messageApi.info(t('pages.groups.emptyForAction'));
return;
}
+ scopeRequest.current++;
setGroupForAction(g);
setRemoveClientsOpen(true);
}
- function onDeleteClients(g: GroupSummary) {
- if (!g.clientCount) {
- messageApi.info(t('pages.groups.emptyForAction'));
- return;
- }
+ async function onDeleteClients(g: GroupSummary) {
+ const scope = await freezeGroup(g);
+ if (!scope) return;
modal.confirm({
title: t('pages.groups.deleteClientsConfirmTitle', { name: g.name }),
- content: t('pages.groups.deleteClientsConfirmContent', { count: g.clientCount }),
+ content: t('pages.groups.deleteClientsConfirmContent', { count: scope.count }),
okText: t('delete'),
okType: 'danger',
cancelText: t('cancel'),
onOk: async () => {
- const emails = await fetchEmailsForGroup(g.name);
- if (emails.length === 0) return;
- const msg = await bulkDelete(emails);
+ const msg = await bulkDelete({ group: scope.group, scopeToken: scope.scopeToken });
if (msg?.success) {
const ok = msg.obj?.deleted ?? 0;
const skipped = msg.obj?.skipped ?? [];
- const failed = skipped.length;
+ const failed = msg.obj?.skippedCount ?? skipped.length;
if (failed === 0) {
messageApi.success(t('pages.groups.deleteClientsSuccess', { count: ok }));
} else {
@@ -750,69 +724,67 @@ export default function GroupsPage() {
/>
-
-
-
+ {subLinksOpen && groupForAction && (
+
+
+
+ )}
-
- {
- const msg = await bulkAdjust(groupEmails, addDays, addBytes, flow, limitHwid, adTag);
- if (msg?.success) {
- const obj = msg.obj ?? { adjusted: 0 };
- messageApi.success(
- t('pages.groups.adjustSuccess', {
- count: obj.adjusted ?? 0,
- name: groupForAction?.name ?? '',
- }),
+ {adjustOpen && adjustScope && (
+
+ {
+ const { group, scopeToken } = adjustScope;
+ const msg = await bulkAdjust(
+ { group, scopeToken },
+ addDays,
+ addBytes,
+ flow,
+ limitHwid,
+ adTag,
+ externalLinks,
);
- return obj;
- }
- return null;
- }}
- />
-
+ if (!msg?.success || !msg.obj) return null;
+ messageApi.success(
+ t('pages.groups.adjustSuccess', { count: msg.obj.adjusted, name: group }),
+ );
+ return msg.obj;
+ }}
+ />
+
+ )}
-
- c.group !== groupForAction?.name)}
- onClose={() => setAddClientsOpen(false)}
- onSubmit={async (emails) => {
- const msg = await bulkAddToGroup(emails, groupForAction?.name ?? '');
- if (msg?.success) {
- return (msg.obj as { affected?: number } | undefined) ?? { affected: 0 };
- }
- return null;
- }}
- />
-
-
-
- c.group === groupForAction?.name)}
- onClose={() => setRemoveClientsOpen(false)}
- onSubmit={async (emails) => {
- const msg = await bulkRemoveFromGroup(emails);
- if (msg?.success) {
- return (msg.obj as { affected?: number } | undefined) ?? { affected: 0 };
- }
- return null;
- }}
- />
-
+ {(addClientsOpen || removeClientsOpen) && groupForAction && (
+
+ {
+ setAddClientsOpen(false);
+ setRemoveClientsOpen(false);
+ }}
+ onSubmit={async (selection) => {
+ const group = groupForAction.name;
+ const msg = addClientsOpen
+ ? await bulkAddToGroup(selection, group)
+ : await bulkRemoveFromGroup({ group, selection });
+ return msg?.success
+ ? ((msg.obj as { affected?: number } | undefined) ?? { affected: 0 })
+ : null;
+ }}
+ />
+
+ )}
);
diff --git a/frontend/src/pages/inbounds/InboundsPage.tsx b/frontend/src/pages/inbounds/InboundsPage.tsx
index 7ffaf5de0..6cfadcdba 100644
--- a/frontend/src/pages/inbounds/InboundsPage.tsx
+++ b/frontend/src/pages/inbounds/InboundsPage.tsx
@@ -173,7 +173,7 @@ export default function InboundsPage() {
const [detachSource, setDetachSource] = useState(null);
const [groupOpen, setGroupOpen] = useState(false);
- const [groupSource, setGroupSource] = useState(null);
+ const [groupSourceID, setGroupSourceID] = useState(null);
const [cloneOpen, setCloneOpen] = useState(false);
const [cloneSource, setCloneSource] = useState(null);
@@ -646,7 +646,6 @@ export default function InboundsPage() {
'clipboard',
'clone',
'attachClients',
- 'addToGroup',
];
let target = dbInbound;
if (hydratingKeys.includes(key)) {
@@ -693,7 +692,7 @@ export default function InboundsPage() {
setDetachOpen(true);
break;
case 'addToGroup':
- setGroupSource(target);
+ setGroupSourceID(target.id);
setGroupOpen(true);
break;
case 'clone':
@@ -874,14 +873,17 @@ export default function InboundsPage() {
source={detachSource}
/>
-
- setGroupOpen(false)}
- onAdded={refresh}
- source={groupSource}
- />
-
+ {groupSourceID !== null && (
+
+ setGroupOpen(false)}
+ onAdded={refresh}
+ inboundId={groupSourceID}
+ count={clientCount[groupSourceID]?.clients ?? 0}
+ />
+
+ )}
import('@/pages/clients/BulkAddToGroupModal'));
interface AddClientsToGroupModalProps {
open: boolean;
- source: DBInbound | null;
+ inboundId: number;
+ count: number;
onClose: () => void;
onAdded?: () => void;
}
-function readClientEmails(settings: unknown): string[] {
- const parsed = coerceInboundJsonField(settings) as { clients?: Array<{ email?: string }> };
- const clients = Array.isArray(parsed?.clients) ? parsed.clients : [];
- return clients.map((c) => (c?.email || '').trim()).filter(Boolean);
-}
-
export default function AddClientsToGroupModal({
open,
- source,
+ inboundId,
+ count,
onClose,
onAdded,
}: AddClientsToGroupModalProps) {
- const [groups, setGroups] = useState([]);
-
- const emails = useMemo(() => (source ? readClientEmails(source.settings) : []), [source]);
-
- useEffect(() => {
- if (!open) return;
- let cancelled = false;
- (async () => {
- const msg = await HttpUtil.get('/panel/api/clients/groups', undefined, { silent: true });
- if (cancelled) return;
- const list = Array.isArray(msg?.obj) ? (msg.obj as Array<{ name?: string }>) : [];
- setGroups(list.map((g) => g?.name || '').filter(Boolean));
- })();
- return () => {
- cancelled = true;
- };
- }, [open]);
-
+ const queryClient = useQueryClient();
+ const groups = useQuery({
+ queryKey: keys.clients.groups(),
+ enabled: open,
+ queryFn: async ({ signal }) => {
+ const response = await HttpUtil.get('/panel/api/clients/groups', undefined, {
+ signal,
+ silent: true,
+ });
+ const result = parseMsg(response, GroupSummaryListSchema, 'clients/groups');
+ if (!result.success) throw new Error(result.msg);
+ return result.obj ?? [];
+ },
+ });
return (
{
- if (!o) onClose();
+ count={count}
+ groups={groups.data?.map((group) => group.name) ?? []}
+ onOpenChange={(value) => {
+ if (!value) onClose();
}}
onSubmit={async (group) => {
- const msg = await HttpUtil.post(
+ const response = await HttpUtil.post<{ affected?: number }>(
'/panel/api/clients/groups/bulkAdd',
- { emails, group },
+ { inboundId, group },
{ headers: { 'Content-Type': 'application/json' } },
);
- if (!msg?.success) return null;
+ if (!response?.success) return null;
+ void queryClient.invalidateQueries({ queryKey: keys.clients.root() });
onAdded?.();
- return (msg.obj as { affected?: number } | undefined) ?? { affected: 0 };
+ return response.obj ?? { affected: 0 };
}}
/>
);
diff --git a/frontend/src/schemas/client.ts b/frontend/src/schemas/client.ts
index d7ca6016e..b45e1e776 100644
--- a/frontend/src/schemas/client.ts
+++ b/frontend/src/schemas/client.ts
@@ -220,6 +220,7 @@ export const ClientHydrateSchema = z.object({
});
export const BulkAdjustResultSchema = z.object({
+ skippedCount: z.number().optional(),
adjusted: z.number(),
skipped: z.array(z.object({ email: z.string(), reason: z.string() })).optional(),
externalLinks: z
@@ -228,6 +229,7 @@ export const BulkAdjustResultSchema = z.object({
});
export const BulkDeleteResultSchema = z.object({
+ skippedCount: z.number().optional(),
deleted: z.number(),
skipped: z.array(z.object({ email: z.string(), reason: z.string() })).optional(),
});
diff --git a/internal/web/controller/client.go b/internal/web/controller/client.go
index 9380e28df..3a54eecdc 100644
--- a/internal/web/controller/client.go
+++ b/internal/web/controller/client.go
@@ -399,6 +399,8 @@ func (a *ClientController) resetAllTraffics(c *gin.Context) {
}
type bulkAdjustRequest struct {
+ Group string `json:"group"`
+ ScopeToken string `json:"scopeToken"`
Emails []string `json:"emails"`
AddDays int `json:"addDays"`
AddBytes int64 `json:"addBytes"`
@@ -414,22 +416,30 @@ func (a *ClientController) bulkAdjust(c *gin.Context) {
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
return
}
+ emails, err := a.resolveGroupBulkEmails(c, req.Emails, req.Group, req.ScopeToken)
+ if err != nil {
+ jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
+ return
+ }
var result service.BulkAdjustResult
var needRestart bool
- var err error
if req.ExternalLinks != nil {
if req.AddDays != 0 || req.AddBytes != 0 || req.Flow != "" || req.LimitHwid != nil || req.AdTag != "" {
jsonMsg(c, "append external links separately from other adjustments", errors.New("externalLinks cannot be combined with other adjustments"))
return
}
- result, err = a.clientService.BulkAppendExternalLinks(req.Emails, req.ExternalLinks)
+ result, err = a.clientService.BulkAppendExternalLinks(emails, req.ExternalLinks)
} else {
- result, needRestart, err = a.clientService.BulkAdjust(&a.inboundService, req.Emails, req.AddDays, req.AddBytes, req.Flow, req.LimitHwid, req.AdTag)
+ result, needRestart, err = a.clientService.BulkAdjust(&a.inboundService, emails, req.AddDays, req.AddBytes, req.Flow, req.LimitHwid, req.AdTag)
}
if err != nil {
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
return
}
+ if req.Group != "" && len(result.Skipped) > 0 {
+ result.SkippedCount = len(result.Skipped)
+ result.Skipped = result.Skipped[:min(len(result.Skipped), 20)]
+ }
jsonObj(c, result, nil)
if needRestart {
a.xrayService.SetToNeedRestart()
@@ -438,10 +448,22 @@ func (a *ClientController) bulkAdjust(c *gin.Context) {
}
type bulkDeleteRequest struct {
+ Group string `json:"group"`
+ ScopeToken string `json:"scopeToken"`
Emails []string `json:"emails"`
KeepTraffic bool `json:"keepTraffic"`
}
+func (a *ClientController) resolveGroupBulkEmails(c *gin.Context, emails []string, group, scopeToken string) ([]string, error) {
+ if group == "" && scopeToken == "" {
+ return emails, nil
+ }
+ if len(emails) != 0 || strings.TrimSpace(group) == "" {
+ return nil, errors.New("use either emails or a group scope")
+ }
+ return a.clientService.GroupOperationEmails(c.Request.Context(), group, scopeToken)
+}
+
type bulkAttachRequest struct {
Emails []string `json:"emails"`
InboundIds []int `json:"inboundIds"`
@@ -503,11 +525,20 @@ func (a *ClientController) bulkDelete(c *gin.Context) {
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
return
}
- result, needRestart, err := a.clientService.BulkDelete(&a.inboundService, req.Emails, req.KeepTraffic)
+ emails, err := a.resolveGroupBulkEmails(c, req.Emails, req.Group, req.ScopeToken)
if err != nil {
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
return
}
+ result, needRestart, err := a.clientService.BulkDelete(&a.inboundService, emails, req.KeepTraffic)
+ if err != nil {
+ jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
+ return
+ }
+ if req.Group != "" && len(result.Skipped) > 0 {
+ result.SkippedCount = len(result.Skipped)
+ result.Skipped = result.Skipped[:min(len(result.Skipped), 20)]
+ }
jsonObj(c, result, nil)
if needRestart {
a.xrayService.SetToNeedRestart()
diff --git a/internal/web/controller/group.go b/internal/web/controller/group.go
index 3abac34b5..11af7517f 100644
--- a/internal/web/controller/group.go
+++ b/internal/web/controller/group.go
@@ -1,8 +1,12 @@
package controller
import (
+ "bufio"
+ "fmt"
+ "net/http"
"strings"
+ "github.com/mhsanaei/3x-ui/v3/internal/logger"
"github.com/mhsanaei/3x-ui/v3/internal/util/common"
"github.com/mhsanaei/3x-ui/v3/internal/web/service"
@@ -10,8 +14,9 @@ import (
)
type GroupController struct {
- clientService service.ClientService
- xrayService service.XrayService
+ clientService service.ClientService
+ xrayService service.XrayService
+ settingService service.SettingService
}
func NewGroupController(g *gin.RouterGroup) *GroupController {
@@ -22,6 +27,8 @@ func NewGroupController(g *gin.RouterGroup) *GroupController {
func (a *GroupController) initRouter(g *gin.RouterGroup) {
g.GET("/groups", a.list)
+ g.GET("/groups/clientPage", a.clientPage)
+ g.GET("/groups/subLinks/export", a.exportSubLinks)
g.GET("/groups/:name/emails", a.emails)
g.POST("/groups/create", a.create)
g.POST("/groups/rename", a.rename)
@@ -158,8 +165,10 @@ func (a *GroupController) resetTraffic(c *gin.Context) {
}
type bulkAddToGroupRequest struct {
- Emails []string `json:"emails"`
- Group string `json:"group"`
+ Emails []string `json:"emails"`
+ Group string `json:"group"`
+ InboundID *int `json:"inboundId"`
+ Selection *service.GroupClientSelection `json:"selection"`
}
func (a *GroupController) bulkAdd(c *gin.Context) {
@@ -172,7 +181,21 @@ func (a *GroupController) bulkAdd(c *gin.Context) {
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), common.NewError("group name is required"))
return
}
- affected, err := a.clientService.AddToGroup(req.Emails, req.Group)
+ if (req.InboundID != nil && (*req.InboundID <= 0 || req.Selection != nil || len(req.Emails) != 0)) ||
+ (req.Selection != nil && len(req.Emails) != 0) {
+ jsonMsg(c, I18nWeb(c, "somethingWentWrong"), common.NewError("use one client scope"))
+ return
+ }
+ var affected int
+ var err error
+ switch {
+ case req.InboundID != nil:
+ affected, err = a.clientService.AddInboundToGroup(c.Request.Context(), *req.InboundID, req.Group)
+ case req.Selection != nil:
+ affected, err = a.clientService.ChangeGroupSelection(c.Request.Context(), req.Group, "add", *req.Selection)
+ default:
+ affected, err = a.clientService.AddToGroup(req.Emails, req.Group)
+ }
if err != nil {
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
return
@@ -182,7 +205,9 @@ func (a *GroupController) bulkAdd(c *gin.Context) {
}
type bulkRemoveFromGroupRequest struct {
- Emails []string `json:"emails"`
+ Emails []string `json:"emails"`
+ Group string `json:"group"`
+ Selection *service.GroupClientSelection `json:"selection"`
}
func (a *GroupController) bulkRemove(c *gin.Context) {
@@ -191,12 +216,79 @@ func (a *GroupController) bulkRemove(c *gin.Context) {
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
return
}
- affected, err := a.clientService.RemoveFromGroup(req.Emails)
+ if (req.Selection != nil && len(req.Emails) != 0) || (req.Selection == nil && req.Group != "") {
+ jsonMsg(c, I18nWeb(c, "somethingWentWrong"), common.NewError("use one client scope"))
+ return
+ }
+ var affected int
+ var err error
+ if req.Selection != nil {
+ affected, err = a.clientService.ChangeGroupSelection(c.Request.Context(), req.Group, "remove", *req.Selection)
+ } else {
+ affected, err = a.clientService.RemoveFromGroup(req.Emails)
+ }
if err != nil {
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
return
}
jsonObj(c, gin.H{"affected": affected}, nil)
- a.xrayService.SetToNeedRestart()
- notifyClientsChanged()
+ if affected > 0 {
+ a.xrayService.SetToNeedRestart()
+ notifyClientsChanged()
+ }
+}
+
+func (a *GroupController) clientPage(c *gin.Context) {
+ var params service.GroupClientPageParams
+ if err := c.ShouldBindQuery(¶ms); err != nil {
+ jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
+ return
+ }
+ page, err := a.clientService.ListGroupClients(c.Request.Context(), params)
+ jsonObj(c, page, err)
+}
+
+func (a *GroupController) exportSubLinks(c *gin.Context) {
+ links, err := a.settingService.GetPanelSubscriptionLinks(c.Request.Host)
+ if err != nil {
+ c.String(http.StatusInternalServerError, "%s", I18nWeb(c, "somethingWentWrong"))
+ return
+ }
+ group := strings.TrimSpace(c.Query("group"))
+ if !links.Enable || links.URI == "" || group == "" {
+ c.String(http.StatusBadRequest, "group and enabled subscriptions are required")
+ return
+ }
+
+ c.Header("Content-Type", "text/plain; charset=utf-8")
+ c.Header("Content-Disposition", `attachment; filename="sub-links.txt"`)
+ c.Header("Cache-Control", "no-store")
+ out := bufio.NewWriter(c.Writer)
+ first := true
+ err = a.clientService.WalkGroupSubscriptionClients(c.Request.Context(), group, func(email, subID string) error {
+ if !first {
+ if err := out.WriteByte('\n'); err != nil {
+ return err
+ }
+ }
+ first = false
+ if _, err := fmt.Fprintf(out, "%s\t%s%s", email, links.URI, subID); err != nil {
+ return err
+ }
+ if links.JSONEnable && links.JSONURI != "" {
+ _, err := fmt.Fprintf(out, "\t%s%s", links.JSONURI, subID)
+ return err
+ }
+ return nil
+ })
+ if err == nil {
+ err = out.Flush()
+ }
+ if err != nil && c.Request.Context().Err() == nil {
+ logger.Warning("group subscription export failed:", err)
+ if !c.Writer.Written() {
+ c.Header("Content-Disposition", "")
+ c.String(http.StatusInternalServerError, "%s", I18nWeb(c, "somethingWentWrong"))
+ }
+ }
}
diff --git a/internal/web/controller/group_client_pages_test.go b/internal/web/controller/group_client_pages_test.go
new file mode 100644
index 000000000..65a6ef3b2
--- /dev/null
+++ b/internal/web/controller/group_client_pages_test.go
@@ -0,0 +1,292 @@
+package controller
+
+import (
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/gin-gonic/gin"
+
+ "github.com/mhsanaei/3x-ui/v3/internal/database"
+ "github.com/mhsanaei/3x-ui/v3/internal/database/dbtest"
+ "github.com/mhsanaei/3x-ui/v3/internal/database/model"
+ "github.com/mhsanaei/3x-ui/v3/internal/testpg"
+ "github.com/mhsanaei/3x-ui/v3/internal/web/service"
+ "github.com/mhsanaei/3x-ui/v3/internal/xray"
+)
+
+const groupAPI = "/panel/api/clients"
+
+func groupTestRouter(t *testing.T) *gin.Engine {
+ t.Helper()
+ cleanup, err := testpg.IsolatePackage("group_client_http")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(cleanup)
+ dbtest.InitDB(t, filepath.Join(t.TempDir(), "x-ui.db"))
+ router := gin.New()
+ routes := router.Group(groupAPI)
+ NewGroupController(routes)
+ NewClientController(routes)
+ return router
+}
+
+func groupAPIRequest(router *gin.Engine, method, route, body string) *httptest.ResponseRecorder {
+ out := httptest.NewRecorder()
+ req := httptest.NewRequest(method, groupAPI+route, strings.NewReader(body))
+ if method == http.MethodPost {
+ req.Header.Set("Content-Type", "application/json")
+ }
+ router.ServeHTTP(out, req)
+ return out
+}
+
+func groupPage(t *testing.T, router *gin.Engine, query string) service.GroupClientPage {
+ t.Helper()
+ out := groupAPIRequest(router, http.MethodGet, "/groups/clientPage?"+query, "")
+ var result struct {
+ Success bool
+ Obj service.GroupClientPage
+ }
+ if err := json.Unmarshal(out.Body.Bytes(), &result); err != nil || !result.Success {
+ t.Fatalf("group page %q returned %s (%v)", query, out.Body, err)
+ }
+ return result.Obj
+}
+
+func groupMutation(t *testing.T, router *gin.Engine, route string, body any, success bool, field string, want int) {
+ t.Helper()
+ payload, err := json.Marshal(body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ out := groupAPIRequest(router, http.MethodPost, route, string(payload))
+ var result struct {
+ Success bool
+ Obj map[string]json.RawMessage
+ }
+ if err := json.Unmarshal(out.Body.Bytes(), &result); err != nil || result.Success != success {
+ t.Fatalf("%s returned %s (wanted success=%t): %v", route, out.Body, success, err)
+ }
+ if success {
+ var got int
+ if err := json.Unmarshal(result.Obj[field], &got); err != nil || got != want {
+ t.Fatalf("%s returned %s, want %s=%d", route, out.Body, field, want)
+ }
+ }
+}
+
+func createTestGroupClients(t *testing.T, size, memberCount int) []model.ClientRecord {
+ t.Helper()
+ db := database.GetDB()
+ if err := db.Create(&model.ClientGroup{Name: "staff"}).Error; err != nil {
+ t.Fatal(err)
+ }
+ rows := make([]model.ClientRecord, size)
+ for i := range rows {
+ rows[i] = model.ClientRecord{Email: fmt.Sprintf("client-%06d", i), SubID: fmt.Sprintf("s-%06d", i), Comment: "literal_%", Group: "previous", TotalGB: 1024, Enable: true}
+ if i < memberCount {
+ rows[i].Group = "staff"
+ }
+ }
+ if err := db.CreateInBatches(rows, 300).Error; err != nil {
+ t.Fatal(err)
+ }
+ return rows
+}
+
+func TestGroupClientPageAndFrozenWriteHTTP(t *testing.T) {
+ router := groupTestRouter(t)
+ rows := createTestGroupClients(t, 230, 110)
+ page := groupPage(t, router, "group=staff&mode=add&page=2")
+ if page.Total != 120 || len(page.Items) != 20 || page.Items[0].ID != rows[210].Id {
+ t.Fatalf("second add page = %d rows out of %d, expected clients 210–229", len(page.Items), page.Total)
+ }
+ search := url.QueryEscape("literal_%")
+ frozen := groupPage(t, router, "group=STAFF&mode=add&freeze=true&search="+search)
+ if frozen.Total != 120 || len(frozen.Items) != 0 || frozen.MaxID != rows[229].Id {
+ t.Fatalf("frozen add scope = %+v", frozen)
+ }
+ db := database.GetDB()
+ newer := model.ClientRecord{Email: "newer", Comment: "literal_%", Group: "previous"}
+ if err := db.Create(&newer).Error; err != nil {
+ t.Fatal(err)
+ }
+ alternate := model.ClientRecord{Email: "wildcard-would-match", Comment: "literalXY", Group: "previous"}
+ if err := db.Create(&alternate).Error; err != nil {
+ t.Fatal(err)
+ }
+ last := groupPage(t, router, fmt.Sprintf("group=staff&mode=add&page=2&maxId=%d&scopeSearch=%s", frozen.MaxID, search))
+ if len(last.Items) != 22 || last.Items[20].InScope || last.Items[21].InScope || !last.Items[19].InScope {
+ t.Fatalf("new and out-of-filter clients were included in the frozen scope: %+v", last.Items)
+ }
+ selection := service.GroupClientSelection{
+ Mode: "allMatching", ScopeToken: frozen.ScopeToken,
+ Search: "literal_%", ExcludedClientIDs: []int{rows[110].Id},
+ }
+ body := map[string]any{"group": "staff", "selection": selection}
+ if err := db.Model(&rows[111]).UpdateColumn("group_name", "staff").Error; err != nil {
+ t.Fatal(err)
+ }
+ groupMutation(t, router, "/groups/bulkAdd", body, false, "", 0)
+ staff := groupPage(t, router, "group=staff&mode=remove")
+ if staff.Total != 111 {
+ t.Fatalf("stale selection changed client groups: staff=%d", staff.Total)
+ }
+ if err := db.Model(&rows[111]).UpdateColumn("group_name", "previous").Error; err != nil {
+ t.Fatal(err)
+ }
+ groupMutation(t, router, "/groups/bulkAdd", body, true, "affected", 119)
+ groupMutation(t, router, "/groups/bulkAdd", body, false, "", 0)
+ for _, id := range []int{rows[110].Id, newer.Id, alternate.Id} {
+ var row model.ClientRecord
+ if err := db.First(&row, id).Error; err != nil || row.Group != "previous" {
+ t.Fatalf("client %d left its group: %q, err=%v", id, row.Group, err)
+ }
+ }
+ selection = service.GroupClientSelection{Mode: "explicit", ClientIDs: []int{rows[0].Id, newer.Id}}
+ groupMutation(t, router, "/groups/bulkRemove", map[string]any{"group": "staff", "selection": selection}, false, "", 0)
+ selection.ClientIDs = []int{rows[0].Id, rows[0].Id}
+ groupMutation(t, router, "/groups/bulkRemove", map[string]any{"group": "staff", "selection": selection}, true, "affected", 1)
+ if page := groupPage(t, router, "group=staff&mode=remove&page=3"); page.Total != 228 || len(page.Items) != 28 {
+ t.Fatalf("remove page after mutations = %d out of %d", len(page.Items), page.Total)
+ }
+}
+
+func TestGroupBulkOperationsRespectFrozenMembersHTTP(t *testing.T) {
+ router := groupTestRouter(t)
+ rows := createTestGroupClients(t, 6, 2)
+ freeze := groupPage(t, router, "group=staff&mode=remove&freeze=true")
+ db := database.GetDB()
+ if err := db.Model(&rows[0]).UpdateColumn("group_name", "previous").Error; err != nil {
+ t.Fatal(err)
+ }
+ groupMutation(t, router, "/bulkDel", map[string]any{"group": "staff", "scopeToken": freeze.ScopeToken}, false, "", 0)
+
+ freeze = groupPage(t, router, "group=staff&mode=remove&freeze=true")
+ body := map[string]any{"group": "staff", "scopeToken": freeze.ScopeToken}
+ newer := model.ClientRecord{Email: "new-member", Group: "staff", TotalGB: 1024}
+ if err := db.Create(&newer).Error; err != nil {
+ t.Fatal(err)
+ }
+ for _, record := range []model.ClientRecord{rows[0], rows[1], newer} {
+ if err := db.Create(&xray.ClientTraffic{Email: record.Email, Total: record.TotalGB, Enable: true}).Error; err != nil {
+ t.Fatal(err)
+ }
+ }
+ groupMutation(t, router, "/bulkAdjust", map[string]any{
+ "group": "staff", "scopeToken": freeze.ScopeToken, "addBytes": 256,
+ }, true, "adjusted", 1)
+ for email, want := range map[string]int64{rows[0].Email: 1024, rows[1].Email: 1280, newer.Email: 1024} {
+ var row xray.ClientTraffic
+ if err := db.Where("email = ?", email).First(&row).Error; err != nil || row.Total != want {
+ t.Fatalf("client %s quota = %d, want %d: %v", email, row.Total, want, err)
+ }
+ }
+ groupMutation(t, router, "/bulkDel", body, true, "deleted", 1)
+ groupMutation(t, router, "/bulkDel", body, false, "", 0)
+ groupMutation(t, router, "/bulkDel", map[string]any{"emails": []string{rows[0].Email}}, true, "deleted", 1)
+ if page := groupPage(t, router, "group=staff&mode=remove"); page.Total != 1 || page.Items[0].ID != newer.Id {
+ t.Fatalf("bulk deletion selected clients outside the frozen scope: %+v", page)
+ }
+}
+
+func TestGroupAdjustCapsReportedSkipsWithoutChangingExplicitResponses(t *testing.T) {
+ router := groupTestRouter(t)
+ rows := createTestGroupClients(t, 25, 25)
+ if err := database.GetDB().Model(&model.ClientRecord{}).
+ Where("group_name = ?", "staff").UpdateColumn("total_gb", 0).Error; err != nil {
+ t.Fatal(err)
+ }
+ emails := make([]string, len(rows))
+ for i, row := range rows {
+ emails[i] = row.Email
+ }
+ var result struct {
+ Success bool
+ Obj service.BulkAdjustResult
+ }
+ groupResponse := groupAPIRequest(router, http.MethodPost, "/bulkAdjust", `{"group":"staff","addBytes":1}`)
+ if err := json.Unmarshal(groupResponse.Body.Bytes(), &result); err != nil || !result.Success ||
+ result.Obj.Adjusted != 0 || len(result.Obj.Skipped) != 20 || result.Obj.SkippedCount != 25 {
+ t.Fatalf("group adjust response = %s (%v)", groupResponse.Body, err)
+ }
+ body, err := json.Marshal(map[string]any{"emails": emails, "addBytes": 1})
+ if err != nil {
+ t.Fatal(err)
+ }
+ out := groupAPIRequest(router, http.MethodPost, "/bulkAdjust", string(body))
+ result.Obj = service.BulkAdjustResult{}
+ if err := json.Unmarshal(out.Body.Bytes(), &result); err != nil || !result.Success ||
+ result.Obj.Adjusted != 0 || len(result.Obj.Skipped) != 25 || strings.Contains(out.Body.String(), "skippedCount") {
+ t.Fatalf("explicit adjust response = %s (%v)", out.Body, err)
+ }
+}
+
+func TestGroupSubscriptionExportAndPagingHTTP(t *testing.T) {
+ sizes := []int{1000}
+ if os.Getenv("XUI_SCALE_TEST") != "" {
+ sizes = append(sizes, 10000, 50000)
+ }
+ for _, size := range sizes {
+ t.Run(fmt.Sprint(size), func(t *testing.T) {
+ testGroupSubscriptionExportAndPaging(t, size)
+ })
+ }
+}
+
+func testGroupSubscriptionExportAndPaging(t *testing.T, size int) {
+ t.Helper()
+ router := groupTestRouter(t)
+ rows := createTestGroupClients(t, size, min(size, 10000))
+ db := database.GetDB()
+ if err := db.Model(&rows[1]).UpdateColumn("sub_id", "").Error; err != nil {
+ t.Fatal(err)
+ }
+ for key, val := range map[string]string{
+ "subEnable": "true", "subURI": "https://sub.example.test/plain/", "subJsonEnable": "true", "subJsonURI": "https://sub.example.test/json/",
+ } {
+ var setting model.Setting
+ if err := db.Where("key = ?", key).Assign(model.Setting{Value: val}).FirstOrCreate(&setting, model.Setting{Key: key}).Error; err != nil {
+ t.Fatal(err)
+ }
+ }
+ total := min(size, 10000) - 1
+ page := groupPage(t, router, "group=staff&mode=links")
+ if os.Getenv("XUI_SCALE_TEST") != "" {
+ pageResponse := groupAPIRequest(router, http.MethodGet, "/groups/clientPage?group=staff&mode=links", "")
+ emailResponse := groupAPIRequest(router, http.MethodGet, "/groups/staff/emails", "")
+ t.Logf("%d clients, %d links: page %d bytes, legacy emails %d bytes", size, total, pageResponse.Body.Len(), emailResponse.Body.Len())
+ }
+ if page.Total != int64(total) || len(page.Items) != 100 || page.Items[1].Email != rows[2].Email {
+ t.Fatalf("link page returned %d rows out of %d", len(page.Items), page.Total)
+ }
+ if size == 50000 {
+ add := groupPage(t, router, "group=staff&mode=add&page=400")
+ if add.Total != 40000 || len(add.Items) != 100 || add.Items[99].Email != rows[49999].Email {
+ t.Fatalf("last page of 40,000 candidates returned %d out of %d", len(add.Items), add.Total)
+ }
+ }
+ out := groupAPIRequest(router, http.MethodGet, "/groups/subLinks/export?group=staff", "")
+ lines := strings.Split(out.Body.String(), "\n")
+ if out.Code != http.StatusOK || out.Header().Get("Cache-Control") != "no-store" || len(lines) != total {
+ t.Fatalf("export returned HTTP %d and %d rows, want %d rows", out.Code, len(lines), total)
+ }
+ for index, line := range lines {
+ if index > 0 {
+ index++
+ }
+ row := rows[index]
+ want := row.Email + "\thttps://sub.example.test/plain/" + row.SubID + "\thttps://sub.example.test/json/" + row.SubID
+ if line != want {
+ t.Fatalf("export row %d = %q, want %q", index, line, want)
+ }
+ }
+}
diff --git a/internal/web/controller/group_client_scope_test.go b/internal/web/controller/group_client_scope_test.go
new file mode 100644
index 000000000..6fd83876a
--- /dev/null
+++ b/internal/web/controller/group_client_scope_test.go
@@ -0,0 +1,85 @@
+package controller
+
+import (
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/gin-gonic/gin"
+
+ "github.com/mhsanaei/3x-ui/v3/internal/database"
+ "github.com/mhsanaei/3x-ui/v3/internal/database/dbtest"
+ "github.com/mhsanaei/3x-ui/v3/internal/database/model"
+ "github.com/mhsanaei/3x-ui/v3/internal/testpg"
+)
+
+func TestGroupBulkAddResolvesInboundMembershipHTTP(t *testing.T) {
+ cleanup, err := testpg.IsolatePackage("group_client_http")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(cleanup)
+ dbtest.InitDB(t, filepath.Join(t.TempDir(), "x-ui.db"))
+ db := database.GetDB()
+ first := model.Inbound{Tag: "source", Port: 50111, Protocol: model.VLESS, Settings: `{"clients":[{"email":"shared"}]}`}
+ second := model.Inbound{Tag: "other", Port: 50112, Protocol: model.VLESS, Settings: `{"clients":[{"email":"shared"},{"email":"other"}]}`}
+ shared := model.ClientRecord{Email: "shared", Group: "previous"}
+ other := model.ClientRecord{Email: "other", Group: "previous"}
+ for _, row := range []any{&first, &second, &shared, &other} {
+ if err := db.Create(row).Error; err != nil {
+ t.Fatal(err)
+ }
+ }
+ links := []model.ClientInbound{
+ {ClientId: shared.Id, InboundId: first.Id},
+ {ClientId: shared.Id, InboundId: second.Id},
+ {ClientId: other.Id, InboundId: second.Id},
+ }
+ if err := db.Create(&links).Error; err != nil {
+ t.Fatal(err)
+ }
+ originalSettings := second.Settings
+ if err := db.Model(&second).UpdateColumn("settings", "{").Error; err != nil {
+ t.Fatal(err)
+ }
+ router := gin.New()
+ NewGroupController(router.Group("/panel/api/clients"))
+ groupMutation(t, router, "/groups/bulkAdd", map[string]any{"group": "staff", "inboundId": first.Id}, false, "", 0)
+ var unchanged model.ClientRecord
+ if err := db.First(&unchanged, shared.Id).Error; err != nil || unchanged.Group != "previous" {
+ t.Fatalf("malformed sibling inbound left a committed group change: %q, err=%v", unchanged.Group, err)
+ }
+ if err := db.Model(&second).UpdateColumn("settings", originalSettings).Error; err != nil {
+ t.Fatal(err)
+ }
+ body := fmt.Sprintf(`{"group":"staff","inboundId":%d}`, first.Id)
+ for _, want := range []int{1, 0} {
+ req := httptest.NewRequest(http.MethodPost, "/panel/api/clients/groups/bulkAdd", strings.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ out := httptest.NewRecorder()
+ router.ServeHTTP(out, req)
+ var result struct {
+ Success bool
+ Obj struct{ Affected int }
+ }
+ if err := json.Unmarshal(out.Body.Bytes(), &result); err != nil || !result.Success || result.Obj.Affected != want {
+ t.Fatalf("group add returned %s, want %d changed: %v", out.Body, want, err)
+ }
+ }
+ for id, want := range map[int]string{shared.Id: "staff", other.Id: "previous"} {
+ var got model.ClientRecord
+ if err := db.First(&got, id).Error; err != nil || got.Group != want {
+ t.Fatalf("client %d group = %q, want %q: %v", id, got.Group, want, err)
+ }
+ }
+ for _, id := range []int{first.Id, second.Id} {
+ var inbound model.Inbound
+ if err := db.First(&inbound, id).Error; err != nil || !strings.Contains(inbound.Settings, `"group":"staff"`) {
+ t.Fatalf("inbound %d settings were not updated: %s (%v)", id, inbound.Settings, err)
+ }
+ }
+}
diff --git a/internal/web/service/client_attach_selection.go b/internal/web/service/client_attach_selection.go
index a02179f11..5b5654f02 100644
--- a/internal/web/service/client_attach_selection.go
+++ b/internal/web/service/client_attach_selection.go
@@ -148,7 +148,7 @@ func filteredAttachCandidates(q *gorm.DB, sourceID int, search, group string) *g
return q
}
-func writeAttachID(h hash.Hash, id int) {
+func writeClientScopeID(h hash.Hash, id int) {
var buf [8]byte
binary.BigEndian.PutUint64(buf[:], uint64(id))
_, _ = h.Write(buf[:])
@@ -156,10 +156,10 @@ func writeAttachID(h hash.Hash, id int) {
func attachScopeHash(sourceID int, targets []int) hash.Hash {
h := sha256.New()
- writeAttachID(h, sourceID)
- writeAttachID(h, len(targets))
+ writeClientScopeID(h, sourceID)
+ writeClientScopeID(h, len(targets))
for _, id := range targets {
- writeAttachID(h, id)
+ writeClientScopeID(h, id)
}
return h
}
@@ -201,14 +201,14 @@ func (s *ClientService) ListAttachCandidates(ctx context.Context, p AttachCandid
if err := rows.Scan(&id); err != nil {
return nil, err
}
- writeAttachID(h, id)
+ writeClientScopeID(h, id)
resp.Eligible++
resp.MaxID = id
}
if err := rows.Err(); err != nil {
return nil, err
}
- writeAttachID(h, resp.MaxID)
+ writeClientScopeID(h, resp.MaxID)
resp.ScopeToken = strconv.Itoa(resp.MaxID) + "." + hex.EncodeToString(h.Sum(nil))
return resp, nil
}
@@ -294,14 +294,14 @@ func (s *ClientService) BulkAttachSelection(ctx context.Context, inboundSvc *Inb
}
records = eligibleRecords[:0]
for _, record := range eligibleRecords {
- writeAttachID(h, record.Id)
+ writeClientScopeID(h, record.Id)
if _, skip := excluded[record.Id]; skip {
delete(excluded, record.Id)
continue
}
records = append(records, record)
}
- writeAttachID(h, maxID)
+ writeClientScopeID(h, maxID)
if len(excluded) > 0 || hex.EncodeToString(h.Sum(nil)) != digest {
return nil, false, stale
}
diff --git a/internal/web/service/client_bulk.go b/internal/web/service/client_bulk.go
index ea249ba19..28f8124cf 100644
--- a/internal/web/service/client_bulk.go
+++ b/internal/web/service/client_bulk.go
@@ -296,6 +296,7 @@ type inboundApplyOutcome struct {
// BulkAdjustResult reports changed clients and per-client skip reasons.
// ExternalLinks contains row counts only for append requests.
type BulkAdjustResult struct {
+ SkippedCount int `json:"skippedCount,omitempty" example:"0"`
Adjusted int `json:"adjusted" example:"2"`
Skipped []BulkAdjustReport `json:"skipped,omitempty" example:"[]"`
ExternalLinks *BulkExternalLinksResult `json:"externalLinks,omitempty"`
@@ -879,8 +880,9 @@ func (s *ClientService) bulkAdjustInboundClients(
// BulkDeleteResult mirrors BulkAdjustResult: total deleted plus per-email
// skip reasons when an email could not be processed.
type BulkDeleteResult struct {
- Deleted int `json:"deleted"`
- Skipped []BulkDeleteReport `json:"skipped,omitempty"`
+ SkippedCount int `json:"skippedCount,omitempty" example:"0"`
+ Deleted int `json:"deleted"`
+ Skipped []BulkDeleteReport `json:"skipped,omitempty"`
}
type BulkDeleteReport struct {
diff --git a/internal/web/service/client_group_scope.go b/internal/web/service/client_group_scope.go
new file mode 100644
index 000000000..186f042e6
--- /dev/null
+++ b/internal/web/service/client_group_scope.go
@@ -0,0 +1,350 @@
+package service
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "hash"
+ "strconv"
+ "strings"
+
+ "gorm.io/gorm"
+
+ "github.com/mhsanaei/3x-ui/v3/internal/database"
+ "github.com/mhsanaei/3x-ui/v3/internal/database/model"
+)
+
+const (
+ groupClientPageSize = 100
+ maxGroupSelectionExclusions = 1000
+)
+
+var errGroupSelectionStale = errors.New("client group selection changed. Reopen the action or select clients again.")
+
+type GroupClientPageParams struct {
+ Group string `form:"group"`
+ Mode string `form:"mode"`
+ Page int `form:"page"`
+ Search string `form:"search"`
+ Freeze bool `form:"freeze"`
+ ScopeSearch string `form:"scopeSearch"`
+ MaxID *int `form:"maxId"`
+}
+
+type GroupClientRow struct {
+ ID int `json:"id" example:"1"`
+ Email string `json:"email" example:"alice"`
+ Comment string `json:"comment" example:"Example client"`
+ Group string `json:"group" example:"staff"`
+ Enable bool `json:"enable" example:"true"`
+ SubID string `json:"subId" example:"example-sub-id"`
+ InScope bool `json:"inScope" example:"true"`
+}
+
+type GroupClientPage struct {
+ Items []GroupClientRow `json:"items"`
+ Total int64 `json:"total" example:"120"`
+ ScopeToken string `json:"scopeToken,omitempty"`
+ MaxID int `json:"maxId,omitempty"`
+}
+
+type GroupClientSelection struct {
+ Mode string `json:"mode" example:"allMatching"`
+ ClientIDs []int `json:"clientIds,omitempty"`
+ ExcludedClientIDs []int `json:"excludedClientIds,omitempty"`
+ ScopeToken string `json:"scopeToken,omitempty"`
+ Search string `json:"search,omitempty"`
+}
+
+type groupClientScope struct {
+ name string
+ mode string
+}
+
+func (scope groupClientScope) candidates(db *gorm.DB) *gorm.DB {
+ q := attachCandidates(db, 0)
+ if scope.mode == "add" {
+ return q.Where("COALESCE(c.group_name, '') <> ?", scope.name)
+ }
+ q = q.Where("c.group_name = ?", scope.name)
+ if scope.mode == "links" {
+ q = q.Where("c.sub_id <> ''")
+ }
+ return q
+}
+
+func findGroupClientScope(db *gorm.DB, group, mode string) (groupClientScope, error) {
+ group = strings.TrimSpace(group)
+ if group == "" || (mode != "add" && mode != "remove" && mode != "links") {
+ return groupClientScope{}, fmt.Errorf("invalid client group scope")
+ }
+ if mode != "add" {
+ return groupClientScope{name: group, mode: mode}, nil
+ }
+ var stored model.ClientGroup
+ err := db.Where("LOWER(name) = LOWER(?)", group).Order("id").Take(&stored).Error
+ if err == nil {
+ return groupClientScope{name: stored.Name, mode: mode}, nil
+ }
+ if !errors.Is(err, gorm.ErrRecordNotFound) {
+ return groupClientScope{}, err
+ }
+ var derived model.ClientRecord
+ err = db.Table("clients").Where("group_name = ?", group).Select("id").Take(&derived).Error
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return groupClientScope{}, fmt.Errorf("client group no longer exists")
+ }
+ return groupClientScope{name: group, mode: mode}, err
+}
+
+func groupSearchCond(needle string) (string, []any) {
+ parts, args := clientTextSearch(caseVariants(needle), []string{"c.email", "c.comment", "c.group_name"})
+ return "(" + strings.Join(parts, " OR ") + ")", args
+}
+
+func groupClientSearch(q *gorm.DB, search string) *gorm.DB {
+ if needle := strings.TrimSpace(search); needle != "" {
+ filter, args := groupSearchCond(needle)
+ return q.Where(filter, args...)
+ }
+ return q
+}
+
+func (scope groupClientScope) digest(search string) hash.Hash {
+ h := sha256.New()
+ for _, part := range []string{"group-client-scope", scope.mode, scope.name, strings.TrimSpace(search)} {
+ writeClientScopeID(h, len(part))
+ _, _ = h.Write([]byte(part))
+ }
+ return h
+}
+
+func groupClientToken(h hash.Hash, maxID int) string {
+ writeClientScopeID(h, maxID)
+ return strconv.Itoa(maxID) + "." + hex.EncodeToString(h.Sum(nil))
+}
+
+func (s *ClientService) ListGroupClients(ctx context.Context, p GroupClientPageParams) (*GroupClientPage, error) {
+ if p.Page < 0 || p.Page > 1_000_000 || len(p.Search) > 1024 || len(p.ScopeSearch) > 1024 ||
+ (p.MaxID != nil && *p.MaxID < 1) || (p.Freeze && p.Mode == "links") {
+ return nil, fmt.Errorf("invalid client group page")
+ }
+ db := database.GetDB().WithContext(ctx)
+ scope, err := findGroupClientScope(db, p.Group, p.Mode)
+ if err != nil {
+ return nil, err
+ }
+ page := &GroupClientPage{Items: []GroupClientRow{}}
+ q := groupClientSearch(scope.candidates(db), p.Search)
+ if p.Freeze {
+ rows, err := q.Select("c.id").Order("c.id").Rows()
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ h := scope.digest(p.Search)
+ for rows.Next() {
+ if err := rows.Scan(&page.MaxID); err != nil {
+ return nil, err
+ }
+ writeClientScopeID(h, page.MaxID)
+ page.Total++
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ page.ScopeToken = groupClientToken(h, page.MaxID)
+ return page, nil
+ }
+
+ if err := q.Session(&gorm.Session{}).Count(&page.Total).Error; err != nil {
+ return nil, err
+ }
+ const fields = "c.id, c.email, COALESCE(c.comment, '') AS comment, COALESCE(c.group_name, '') AS \"group\", COALESCE(c.enable, false) AS enable, COALESCE(c.sub_id, '') AS sub_id, "
+ inScope := "true"
+ var args []any
+ if p.MaxID != nil {
+ inScope = "(c.id <= ?)"
+ args = append(args, *p.MaxID)
+ if needle := strings.TrimSpace(p.ScopeSearch); needle != "" {
+ filter, filterArgs := groupSearchCond(needle)
+ inScope = "(" + inScope + " AND COALESCE(" + filter + ", false))"
+ args = append(args, filterArgs...)
+ }
+ }
+ order := "c.id"
+ if p.Mode == "links" {
+ order = "c.email, c.id"
+ }
+ err = q.Select(fields+inScope+" AS in_scope", args...).Order(order).
+ Offset(max(0, p.Page-1) * groupClientPageSize).Limit(groupClientPageSize).Scan(&page.Items).Error
+ return page, err
+}
+
+func (scope groupClientScope) selectionEmails(db *gorm.DB, selection GroupClientSelection) ([]string, error) {
+ q := scope.candidates(db)
+ switch selection.Mode {
+ case "explicit":
+ if len(selection.ClientIDs) == 0 || len(selection.ClientIDs) > 50_000 || selection.ScopeToken != "" ||
+ len(selection.ExcludedClientIDs) != 0 || selection.Search != "" {
+ return nil, fmt.Errorf("invalid explicit client group selection")
+ }
+ ids := uniqueInts(selection.ClientIDs)
+ var emails []string
+ for _, chunk := range chunkInts(ids, sqlInChunk) {
+ var part []string
+ if err := q.Session(&gorm.Session{}).Where("c.id IN ?", chunk).Pluck("c.email", &part).Error; err != nil {
+ return nil, err
+ }
+ if len(part) != len(chunk) {
+ return nil, errGroupSelectionStale
+ }
+ emails = append(emails, part...)
+ }
+ return emails, nil
+ case "allMatching":
+ return scope.frozenEmails(q, selection)
+ default:
+ return nil, fmt.Errorf("invalid client group selection mode")
+ }
+}
+
+func (scope groupClientScope) frozenEmails(q *gorm.DB, selection GroupClientSelection) ([]string, error) {
+ cutoff, digest, ok := strings.Cut(selection.ScopeToken, ".")
+ maxID, parseErr := strconv.Atoi(cutoff)
+ if !ok || parseErr != nil || maxID < 0 || len(digest) != sha256.Size*2 || len(selection.ClientIDs) != 0 ||
+ len(selection.ExcludedClientIDs) > maxGroupSelectionExclusions || len(selection.Search) > 1024 {
+ return nil, fmt.Errorf("invalid frozen client group selection")
+ }
+ excluded := make(map[int]struct{}, len(selection.ExcludedClientIDs))
+ for _, id := range selection.ExcludedClientIDs {
+ excluded[id] = struct{}{}
+ }
+ rows, err := groupClientSearch(q, selection.Search).Where("c.id <= ?", maxID).
+ Select("c.id, c.email").Order("c.id").Rows()
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ h := scope.digest(selection.Search)
+ var emails []string
+ for rows.Next() {
+ var id int
+ var email string
+ if err := rows.Scan(&id, &email); err != nil {
+ return nil, err
+ }
+ writeClientScopeID(h, id)
+ if _, skip := excluded[id]; skip {
+ delete(excluded, id)
+ } else {
+ emails = append(emails, email)
+ }
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ if len(excluded) != 0 || groupClientToken(h, maxID) != selection.ScopeToken {
+ return nil, errGroupSelectionStale
+ }
+ return emails, nil
+}
+
+func (s *ClientService) GroupOperationEmails(ctx context.Context, group, token string) ([]string, error) {
+ db := database.GetDB().WithContext(ctx)
+ scope, err := findGroupClientScope(db, group, "remove")
+ if err != nil {
+ return nil, err
+ }
+ if token != "" {
+ return scope.selectionEmails(db, GroupClientSelection{Mode: "allMatching", ScopeToken: token})
+ }
+ var emails []string
+ err = scope.candidates(db).Order("c.id").Pluck("c.email", &emails).Error
+ return emails, err
+}
+
+func (s *ClientService) ChangeGroupSelection(ctx context.Context, group, mode string, selection GroupClientSelection) (int, error) {
+ if mode != "add" && mode != "remove" {
+ return 0, fmt.Errorf("invalid client group action")
+ }
+ var affected int
+ err := runSerializedTx(func(tx *gorm.DB) error {
+ tx = tx.WithContext(ctx)
+ scope, err := findGroupClientScope(tx, group, mode)
+ if err != nil {
+ return err
+ }
+ emails, err := scope.selectionEmails(tx, selection)
+ if err != nil {
+ return err
+ }
+ target := ""
+ if mode == "add" && len(emails) != 0 {
+ record, err := database.EnsureClientGroup(tx, scope.name)
+ if err != nil {
+ return err
+ }
+ target = record.Name
+ }
+ affected, err = applyClientGroup(tx, emails, target)
+ return err
+ })
+ return affected, err
+}
+
+func (s *ClientService) AddInboundToGroup(ctx context.Context, inboundID int, group string) (int, error) {
+ if inboundID <= 0 {
+ return 0, fmt.Errorf("invalid source inbound ID")
+ }
+ var affected int
+ err := runSerializedTx(func(tx *gorm.DB) error {
+ tx = tx.WithContext(ctx)
+ var inbound model.Inbound
+ if err := tx.Select("id").First(&inbound, inboundID).Error; err != nil {
+ return err
+ }
+ var emails []string
+ if err := attachCandidates(tx, inbound.Id).Pluck("c.email", &emails).Error; err != nil {
+ return err
+ }
+ if len(emails) == 0 {
+ return nil
+ }
+ target, err := database.EnsureClientGroup(tx, group)
+ if err != nil {
+ return err
+ }
+ if target == nil {
+ return fmt.Errorf("group name is required")
+ }
+ affected, err = applyClientGroup(tx, emails, target.Name)
+ return err
+ })
+ return affected, err
+}
+
+func (s *ClientService) WalkGroupSubscriptionClients(ctx context.Context, group string, visit func(email, subID string) error) error {
+ db := database.GetDB().WithContext(ctx)
+ scope, err := findGroupClientScope(db, group, "links")
+ if err != nil {
+ return err
+ }
+ rows, err := scope.candidates(db).Select("c.email, c.sub_id").Order("c.email, c.id").Rows()
+ if err != nil {
+ return err
+ }
+ defer rows.Close()
+ for rows.Next() {
+ var email, subID string
+ if err := rows.Scan(&email, &subID); err != nil {
+ return err
+ }
+ if err := visit(email, subID); err != nil {
+ return err
+ }
+ }
+ return rows.Err()
+}
diff --git a/internal/web/service/client_groups.go b/internal/web/service/client_groups.go
index 5bee1cd68..052c908cd 100644
--- a/internal/web/service/client_groups.go
+++ b/internal/web/service/client_groups.go
@@ -340,129 +340,132 @@ func (s *ClientService) AddToGroup(emails []string, group string) (int, error) {
if len(emails) == 0 {
return 0, nil
}
- db := database.GetDB()
-
- if group != "" {
- record, err := database.EnsureClientGroup(db, group)
- if err != nil {
- return 0, err
+ var affected int
+ err := runSerializedTx(func(tx *gorm.DB) error {
+ if group != "" {
+ record, err := database.EnsureClientGroup(tx, group)
+ if err != nil {
+ return err
+ }
+ group = record.Name
}
- group = record.Name
- }
+ var err error
+ affected, err = applyClientGroup(tx, emails, group)
+ return err
+ })
+ return affected, err
+}
- var records []model.ClientRecord
- for _, batch := range chunkStrings(emails, sqlInChunk) {
- var rows []model.ClientRecord
- if err := db.Where("email IN ?", batch).
- Where("group_name IS NULL OR group_name <> ?", group).
- Find(&rows).Error; err != nil {
- return 0, err
- }
- records = append(records, rows...)
- }
- if len(records) == 0 {
- return 0, nil
- }
- affectedEmails := make([]string, 0, len(records))
- for _, r := range records {
- affectedEmails = append(affectedEmails, r.Email)
- }
-
- tx := db.Begin()
+func applyClientGroup(tx *gorm.DB, emails []string, group string) (int, error) {
+ var affectedEmails []string
var affected int64
- for _, batch := range chunkStrings(affectedEmails, sqlInChunk) {
- result := tx.Model(&model.ClientRecord{}).
- Where("email IN ?", batch).
- Where("group_name IS NULL OR group_name <> ?", group).
- UpdateColumn("group_name", group)
+ inboundIDs := make(map[int]struct{})
+ for _, batch := range chunkStrings(emails, sqlInChunk) {
+ var changed []string
+ if err := tx.Model(&model.ClientRecord{}).
+ Where("email IN ? AND (group_name IS NULL OR group_name <> ?)", batch, group).
+ Pluck("email", &changed).Error; err != nil {
+ return 0, err
+ }
+ if len(changed) == 0 {
+ continue
+ }
+ result := tx.Model(&model.ClientRecord{}).Where("email IN ?", changed).UpdateColumn("group_name", group)
if result.Error != nil {
- tx.Rollback()
return 0, result.Error
}
affected += result.RowsAffected
- }
+ affectedEmails = append(affectedEmails, changed...)
- var inboundIDs []int
- inboundIDSeen := make(map[int]struct{})
- for _, batch := range chunkStrings(affectedEmails, sqlInChunk) {
var ids []int
if err := tx.Table("client_inbounds").
Joins("JOIN clients ON clients.id = client_inbounds.client_id").
- Where("clients.email IN ?", batch).
+ Where("clients.email IN ?", changed).
Distinct("client_inbounds.inbound_id").
Pluck("inbound_id", &ids).Error; err != nil {
- tx.Rollback()
return 0, err
}
for _, id := range ids {
- if _, ok := inboundIDSeen[id]; !ok {
- inboundIDSeen[id] = struct{}{}
- inboundIDs = append(inboundIDs, id)
- }
+ inboundIDs[id] = struct{}{}
}
}
-
emailSet := make(map[string]struct{}, len(affectedEmails))
- for _, e := range affectedEmails {
- emailSet[e] = struct{}{}
+ for _, email := range affectedEmails {
+ emailSet[email] = struct{}{}
}
-
- for _, ibID := range inboundIDs {
+ dirtyNodes := make(map[int]struct{})
+ for _, id := range sortedInboundIds(inboundIDs) {
var ib model.Inbound
- if err := tx.First(&ib, ibID).Error; err != nil {
- tx.Rollback()
+ if err := tx.Select("id", "settings", "node_id").First(&ib, id).Error; err != nil {
return 0, err
}
- var settings map[string]any
- if err := json.Unmarshal([]byte(ib.Settings), &settings); err != nil {
- continue
+ settings, changed, err := patchInboundClientGroup(ib.Settings, emailSet, group)
+ if err != nil {
+ return 0, err
}
- clients, ok := settings["clients"].([]any)
- if !ok {
- continue
- }
- modified := false
- for i := range clients {
- cm, ok := clients[i].(map[string]any)
- if !ok {
- continue
- }
- email, _ := cm["email"].(string)
- if _, hit := emailSet[email]; !hit {
- continue
- }
- if group == "" {
- delete(cm, "group")
- } else {
- cm["group"] = group
- }
- clients[i] = cm
- modified = true
- }
- if modified {
- settings["clients"] = clients
- newSettings, err := json.Marshal(settings)
- if err != nil {
- continue
- }
- ib.Settings = string(newSettings)
- if err := tx.Save(&ib).Error; err != nil {
- tx.Rollback()
+ if changed {
+ if err := tx.Model(&ib).UpdateColumn("settings", settings).Error; err != nil {
return 0, err
}
+ if ib.NodeID != nil {
+ dirtyNodes[*ib.NodeID] = struct{}{}
+ }
}
}
-
- if err := tx.Commit().Error; err != nil {
- return 0, err
+ for _, id := range sortedInboundIds(dirtyNodes) {
+ if err := (&NodeService{}).MarkNodeDirtyTx(tx, id); err != nil {
+ return 0, err
+ }
}
return int(affected), nil
}
+func patchInboundClientGroup(raw string, emails map[string]struct{}, group string) (string, bool, error) {
+ settings, entries, ok := splitSettingsClients(raw)
+ if !ok {
+ return "", false, common.NewError("invalid inbound client settings")
+ }
+ groupValue, err := json.Marshal(group)
+ if err != nil {
+ return "", false, err
+ }
+ changed := false
+ for i, entry := range entries {
+ client, ok := readSettingsClient(entry)
+ if !ok {
+ continue
+ }
+ if _, match := emails[client.Email]; !match {
+ continue
+ }
+ var fields map[string]json.RawMessage
+ if err := json.Unmarshal(entry, &fields); err != nil {
+ return "", false, err
+ }
+ if group == "" {
+ delete(fields, "group")
+ } else {
+ fields["group"] = groupValue
+ }
+ entries[i], err = json.Marshal(fields)
+ if err != nil {
+ return "", false, err
+ }
+ changed = true
+ }
+ if !changed {
+ return raw, false, nil
+ }
+ out, ok := joinSettingsClients(raw, settings, entries)
+ if !ok {
+ return "", false, common.NewError("invalid inbound client settings")
+ }
+ return out, true, nil
+}
+
func (s *ClientService) replaceGroupValue(oldName, newName string, hostGroupIDs *[]string) (int, error) {
- db := database.GetDB()
affected := 0
- err := db.Transaction(func(tx *gorm.DB) error {
+ err := runSerializedTx(func(tx *gorm.DB) error {
var hostGroupValues []string
if hostGroupIDs != nil {
hostGroupValues = normalizeHostGroupIDs(*hostGroupIDs)
diff --git a/internal/web/service/client_paging.go b/internal/web/service/client_paging.go
index 8c3c0e55f..98814826d 100644
--- a/internal/web/service/client_paging.go
+++ b/internal/web/service/client_paging.go
@@ -140,10 +140,17 @@ func caseVariants(s string) []string {
// clientSearchCond builds the search predicate for the given needle variants
// (lowered first) and returns its arguments.
func clientSearchCond(variants []string) (string, []any) {
+ parts, args := clientTextSearch(variants, clientSearchCols)
+ parts = append(parts, "(COALESCE(c.tg_id, 0) <> 0 AND CAST(c.tg_id AS TEXT) LIKE ? ESCAPE '\\')")
+ args = append(args, "%"+escapeLikeLiteral(variants[0])+"%")
+ return "(" + strings.Join(parts, " OR ") + ")", args
+}
+
+func clientTextSearch(variants, columns []string) ([]string, []any) {
var parts []string
var args []any
like := func(v string) string { return "%" + escapeLikeLiteral(v) + "%" }
- for _, col := range clientSearchCols {
+ for _, col := range columns {
parts = append(parts, "LOWER("+col+") LIKE ? ESCAPE '\\'")
args = append(args, like(variants[0]))
for _, v := range variants {
@@ -151,9 +158,7 @@ func clientSearchCond(variants []string) (string, []any) {
args = append(args, like(v))
}
}
- parts = append(parts, "(COALESCE(c.tg_id, 0) <> 0 AND CAST(c.tg_id AS TEXT) LIKE ? ESCAPE '\\')")
- args = append(args, like(variants[0]))
- return "(" + strings.Join(parts, " OR ") + ")", args
+ return parts, args
}
// clientQuery builds the statements behind the clients page: a clients row
diff --git a/internal/web/service/setting.go b/internal/web/service/setting.go
index f801e920e..3857f46ed 100644
--- a/internal/web/service/setting.go
+++ b/internal/web/service/setting.go
@@ -2123,6 +2123,42 @@ func (s *SettingService) BuildSubURIBase(host string) string {
return fmt.Sprintf("%s://%s:%d", scheme, subDomain, subPort)
}
+type PanelSubscriptionLinks struct {
+ Enable bool
+ JSONEnable bool
+ URI string
+ JSONURI string
+}
+
+func (s *SettingService) GetPanelSubscriptionLinks(host string) (PanelSubscriptionLinks, error) {
+ var links PanelSubscriptionLinks
+ var err error
+ if links.Enable, err = s.GetSubEnable(); err != nil {
+ return links, err
+ }
+ if links.JSONEnable, err = s.GetSubJsonEnable(); err != nil {
+ return links, err
+ }
+ if links.URI, err = s.GetSubURI(); err != nil {
+ return links, err
+ }
+ if links.JSONURI, err = s.GetSubJsonURI(); err != nil {
+ return links, err
+ }
+ if (links.Enable && links.URI == "") || (links.JSONEnable && links.JSONURI == "") {
+ base := s.BuildSubURIBase(host)
+ if links.Enable && links.URI == "" {
+ path, _ := s.GetSubPath()
+ links.URI = base + path
+ }
+ if links.JSONEnable && links.JSONURI == "" {
+ path, _ := s.GetSubJsonPath()
+ links.JSONURI = base + path
+ }
+ }
+ return links, nil
+}
+
func (s *SettingService) GetDefaultSettings(host string) (any, error) {
type settingFunc func() (any, error)
settings := map[string]settingFunc{
@@ -2134,12 +2170,8 @@ func (s *SettingService) GetDefaultSettings(host string) (any, error) {
"tgBotEnable": func() (any, error) { return s.GetTgbotEnabled() },
"subThemeDir": func() (any, error) { return s.GetSubThemeDir() },
"happLinkEnable": func() (any, error) { return s.GetHappLinkEnable() },
- "subEnable": func() (any, error) { return s.GetSubEnable() },
- "subJsonEnable": func() (any, error) { return s.GetSubJsonEnable() },
"subClashEnable": func() (any, error) { return s.GetSubClashEnable() },
"subTitle": func() (any, error) { return s.GetSubTitle() },
- "subURI": func() (any, error) { return s.GetSubURI() },
- "subJsonURI": func() (any, error) { return s.GetSubJsonURI() },
"subClashURI": func() (any, error) { return s.GetSubClashURI() },
"datepicker": func() (any, error) { return s.GetDatepicker() },
"ipLimitEnable": func() (any, error) { return s.GetIpLimitEnable() },
@@ -2160,39 +2192,18 @@ func (s *SettingService) GetDefaultSettings(host string) (any, error) {
result[key] = value
}
- subEnable := result["subEnable"].(bool)
- subJsonEnable := false
- if v, ok := result["subJsonEnable"]; ok {
- if b, ok2 := v.(bool); ok2 {
- subJsonEnable = b
- }
+ links, err := s.GetPanelSubscriptionLinks(host)
+ if err != nil {
+ return "", err
}
- subClashEnable := false
- if v, ok := result["subClashEnable"]; ok {
- if b, ok2 := v.(bool); ok2 {
- subClashEnable = b
- }
+ result["subEnable"] = links.Enable
+ result["subJsonEnable"] = links.JSONEnable
+ result["subURI"] = links.URI
+ result["subJsonURI"] = links.JSONURI
+ if result["subClashEnable"].(bool) && result["subClashURI"].(string) == "" {
+ path, _ := s.GetSubClashPath()
+ result["subClashURI"] = s.BuildSubURIBase(host) + path
}
- if (subEnable && result["subURI"].(string) == "") || (subJsonEnable && result["subJsonURI"].(string) == "") || (subClashEnable && result["subClashURI"].(string) == "") {
- subURI := s.BuildSubURIBase(host)
- subTitle, _ := s.GetSubTitle()
- subPath, _ := s.GetSubPath()
- subJsonPath, _ := s.GetSubJsonPath()
- subClashPath, _ := s.GetSubClashPath()
- if subEnable && result["subURI"].(string) == "" {
- result["subURI"] = subURI + subPath
- }
- if result["subTitle"].(string) == "" {
- result["subTitle"] = subTitle
- }
- if subJsonEnable && result["subJsonURI"].(string) == "" {
- result["subJsonURI"] = subURI + subJsonPath
- }
- if subClashEnable && result["subClashURI"].(string) == "" {
- result["subClashURI"] = subURI + subClashPath
- }
- }
-
return result, nil
}
diff --git a/internal/web/translation/ar-EG.json b/internal/web/translation/ar-EG.json
index 7238b0965..fc6697f0b 100644
--- a/internal/web/translation/ar-EG.json
+++ b/internal/web/translation/ar-EG.json
@@ -1202,6 +1202,8 @@
"addToGroupEmpty": "لا يوجد عملاء آخرون للإضافة.",
"addToGroupResult": "تمت إضافة {count} عميل إلى {name}.",
"removeFromGroup": "إزالة عملاء…",
+ "selectAllMatching": "تحديد كل العملاء المطابقين",
+ "selectionLimit": "الحد الأقصى للاختيارات أو الاستثناءات هو {count}.",
"removeFromGroupTitle": "إزالة عملاء من المجموعة «{name}»",
"removeFromGroupDesc": "اختر الأعضاء لإزالتهم من هذه المجموعة. يُحفظ العملاء (استخدم «حذف عملاء المجموعة» للإزالة الكاملة).",
"removeFromGroupResult": "تمت إزالة {count} عميل من {name}.",
diff --git a/internal/web/translation/en-US.json b/internal/web/translation/en-US.json
index 5df5f1e61..4d82ec559 100644
--- a/internal/web/translation/en-US.json
+++ b/internal/web/translation/en-US.json
@@ -1202,6 +1202,8 @@
"addToGroupEmpty": "No other clients available to add.",
"addToGroupResult": "Added {count} client(s) to {name}.",
"removeFromGroup": "Remove clients…",
+ "selectAllMatching": "Select all matching clients",
+ "selectionLimit": "Limit selections or exclusions to {count}.",
"removeFromGroupTitle": "Remove clients from group \"{name}\"",
"removeFromGroupDesc": "Select members to remove from this group. Clients themselves are kept (use \"Delete clients in group\" to remove them entirely).",
"removeFromGroupResult": "Removed {count} client(s) from {name}.",
diff --git a/internal/web/translation/es-ES.json b/internal/web/translation/es-ES.json
index df05bd18f..65023c1bd 100644
--- a/internal/web/translation/es-ES.json
+++ b/internal/web/translation/es-ES.json
@@ -1202,6 +1202,8 @@
"addToGroupEmpty": "No hay otros clientes disponibles para añadir.",
"addToGroupResult": "Añadidos {count} cliente(s) a {name}.",
"removeFromGroup": "Quitar clientes…",
+ "selectAllMatching": "Seleccionar todos los clientes coincidentes",
+ "selectionLimit": "Limita la selección o las exclusiones a {count}.",
"removeFromGroupTitle": "Quitar clientes del grupo «{name}»",
"removeFromGroupDesc": "Selecciona miembros para quitar de este grupo. Los clientes se conservan (usa «Eliminar clientes del grupo» para eliminarlos por completo).",
"removeFromGroupResult": "Quitados {count} cliente(s) de {name}.",
diff --git a/internal/web/translation/fa-IR.json b/internal/web/translation/fa-IR.json
index b89862162..b4c7f4f93 100644
--- a/internal/web/translation/fa-IR.json
+++ b/internal/web/translation/fa-IR.json
@@ -1202,6 +1202,8 @@
"addToGroupEmpty": "کاربر دیگری برای افزودن در دسترس نیست.",
"addToGroupResult": "{count} کاربر به {name} اضافه شد.",
"removeFromGroup": "حذف کاربران…",
+ "selectAllMatching": "انتخاب همهٔ کاربران مطابق جستجو",
+ "selectionLimit": "تعداد انتخابها یا استثناها را به {count} محدود کنید.",
"removeFromGroupTitle": "حذف کاربران از گروه «{name}»",
"removeFromGroupDesc": "اعضایی را برای حذف از این گروه انتخاب کنید. خود کاربران حفظ میشوند (برای حذف کامل از «حذف کاربران گروه» استفاده کنید).",
"removeFromGroupResult": "{count} کاربر از {name} حذف شد.",
diff --git a/internal/web/translation/id-ID.json b/internal/web/translation/id-ID.json
index 77df99297..1490a9267 100644
--- a/internal/web/translation/id-ID.json
+++ b/internal/web/translation/id-ID.json
@@ -1202,6 +1202,8 @@
"addToGroupEmpty": "Tidak ada klien lain untuk ditambahkan.",
"addToGroupResult": "{count} klien ditambahkan ke {name}.",
"removeFromGroup": "Hapus klien…",
+ "selectAllMatching": "Pilih semua klien yang cocok",
+ "selectionLimit": "Batasi pilihan atau pengecualian hingga {count}.",
"removeFromGroupTitle": "Hapus klien dari grup «{name}»",
"removeFromGroupDesc": "Pilih anggota untuk dihapus dari grup ini. Klien tetap dipertahankan (gunakan «Hapus klien di grup» untuk menghapus sepenuhnya).",
"removeFromGroupResult": "{count} klien dihapus dari {name}.",
diff --git a/internal/web/translation/ja-JP.json b/internal/web/translation/ja-JP.json
index 34cdd4de0..fed3bb1cf 100644
--- a/internal/web/translation/ja-JP.json
+++ b/internal/web/translation/ja-JP.json
@@ -1202,6 +1202,8 @@
"addToGroupEmpty": "追加可能な他のクライアントはありません。",
"addToGroupResult": "{count} クライアントを {name} に追加しました。",
"removeFromGroup": "クライアントを削除…",
+ "selectAllMatching": "一致するクライアントをすべて選択",
+ "selectionLimit": "選択または除外は {count} 件までです。",
"removeFromGroupTitle": "グループ「{name}」からクライアントを削除",
"removeFromGroupDesc": "このグループから外すメンバーを選択してください。クライアント自体は保持されます (完全に削除するには「グループのクライアントを削除」を使用)。",
"removeFromGroupResult": "{count} クライアントを {name} から外しました。",
diff --git a/internal/web/translation/pt-BR.json b/internal/web/translation/pt-BR.json
index 781f6cdb6..96872dda3 100644
--- a/internal/web/translation/pt-BR.json
+++ b/internal/web/translation/pt-BR.json
@@ -1202,6 +1202,8 @@
"addToGroupEmpty": "Não há outros clientes disponíveis para adicionar.",
"addToGroupResult": "Adicionados {count} cliente(s) a {name}.",
"removeFromGroup": "Remover clientes…",
+ "selectAllMatching": "Selecionar todos os clientes correspondentes",
+ "selectionLimit": "Limite as seleções ou exclusões a {count}.",
"removeFromGroupTitle": "Remover clientes do grupo «{name}»",
"removeFromGroupDesc": "Selecione membros para remover deste grupo. Os clientes em si são mantidos (use «Excluir clientes do grupo» para removê-los por completo).",
"removeFromGroupResult": "Removidos {count} cliente(s) de {name}.",
diff --git a/internal/web/translation/ru-RU.json b/internal/web/translation/ru-RU.json
index 5b5065d8f..5fd430e96 100644
--- a/internal/web/translation/ru-RU.json
+++ b/internal/web/translation/ru-RU.json
@@ -1202,6 +1202,8 @@
"addToGroupEmpty": "Нет других клиентов для добавления.",
"addToGroupResult": "Добавлено {count} клиент(ов) в {name}.",
"removeFromGroup": "Удалить клиентов…",
+ "selectAllMatching": "Выбрать всех подходящих клиентов",
+ "selectionLimit": "Ограничьте число выбранных или исключённых клиентов до {count}.",
"removeFromGroupTitle": "Удалить клиентов из группы «{name}»",
"removeFromGroupDesc": "Выберите участников для удаления из этой группы. Сами клиенты сохраняются (используйте «Удалить клиентов группы» для полного удаления).",
"removeFromGroupResult": "Удалено {count} клиент(ов) из {name}.",
diff --git a/internal/web/translation/sk-SK.json b/internal/web/translation/sk-SK.json
index 175906240..18797252a 100644
--- a/internal/web/translation/sk-SK.json
+++ b/internal/web/translation/sk-SK.json
@@ -1202,6 +1202,8 @@
"addToGroupEmpty": "Nie sú dostupní žiadni ďalší klienti na pridanie.",
"addToGroupResult": "Pridané do skupiny {name}: {count}.",
"removeFromGroup": "Odobrať klientov…",
+ "selectAllMatching": "Vybrať všetkých zodpovedajúcich klientov",
+ "selectionLimit": "Obmedzte počet vybraných alebo vylúčených klientov na {count}.",
"removeFromGroupTitle": "Odobrať klientov zo skupiny „{name}“",
"removeFromGroupDesc": "Vyberte členov, ktorých chcete odobrať zo skupiny. Samotní klienti zostanú zachovaní. Na ich úplné odstránenie použite akciu „Odstrániť klientov v skupine“.",
"removeFromGroupResult": "Odobraté zo skupiny {name}: {count}.",
diff --git a/internal/web/translation/tr-TR.json b/internal/web/translation/tr-TR.json
index fbab4b889..0b849f394 100644
--- a/internal/web/translation/tr-TR.json
+++ b/internal/web/translation/tr-TR.json
@@ -1202,6 +1202,8 @@
"addToGroupEmpty": "Eklenecek başka kullanıcı yok.",
"addToGroupResult": "{count} kullanıcı {name} grubuna eklendi.",
"removeFromGroup": "Kullanıcı Çıkar…",
+ "selectAllMatching": "Eşleşen tüm istemcileri seç",
+ "selectionLimit": "Seçimleri veya hariç tutulanları {count} ile sınırlandırın.",
"removeFromGroupTitle": "«{name}» Grubundan Kullanıcı Çıkar",
"removeFromGroupDesc": "Bu gruptan çıkarılacak üyeleri seçin. Kullanıcılar korunur (tamamen kaldırmak için «Gruptaki kullanıcıları sil» kullanın).",
"removeFromGroupResult": "{name} grubundan {count} kullanıcı çıkarıldı.",
diff --git a/internal/web/translation/uk-UA.json b/internal/web/translation/uk-UA.json
index fb302d746..a06eff8e9 100644
--- a/internal/web/translation/uk-UA.json
+++ b/internal/web/translation/uk-UA.json
@@ -1202,6 +1202,8 @@
"addToGroupEmpty": "Немає інших клієнтів для додавання.",
"addToGroupResult": "Додано {count} клієнт(ів) до {name}.",
"removeFromGroup": "Видалити клієнтів…",
+ "selectAllMatching": "Вибрати всіх відповідних клієнтів",
+ "selectionLimit": "Обмежте кількість вибраних або виключених клієнтів до {count}.",
"removeFromGroupTitle": "Видалити клієнтів з групи «{name}»",
"removeFromGroupDesc": "Виберіть учасників для видалення з цієї групи. Самі клієнти зберігаються (використовуйте «Видалити клієнтів групи» для повного видалення).",
"removeFromGroupResult": "Видалено {count} клієнт(ів) з {name}.",
diff --git a/internal/web/translation/vi-VN.json b/internal/web/translation/vi-VN.json
index 52570f998..293ec83d5 100644
--- a/internal/web/translation/vi-VN.json
+++ b/internal/web/translation/vi-VN.json
@@ -1202,6 +1202,8 @@
"addToGroupEmpty": "Không có client khác để thêm.",
"addToGroupResult": "Đã thêm {count} client vào {name}.",
"removeFromGroup": "Xóa client…",
+ "selectAllMatching": "Chọn tất cả máy khách phù hợp",
+ "selectionLimit": "Giới hạn lựa chọn hoặc ngoại lệ ở mức {count}.",
"removeFromGroupTitle": "Xóa client khỏi nhóm «{name}»",
"removeFromGroupDesc": "Chọn thành viên để xóa khỏi nhóm này. Bản thân client được giữ lại (dùng «Xóa client trong nhóm» để xóa hoàn toàn).",
"removeFromGroupResult": "Đã xóa {count} client khỏi {name}.",
diff --git a/internal/web/translation/zh-CN.json b/internal/web/translation/zh-CN.json
index d10a4f91b..60d94a257 100644
--- a/internal/web/translation/zh-CN.json
+++ b/internal/web/translation/zh-CN.json
@@ -1202,6 +1202,8 @@
"addToGroupEmpty": "没有其他可添加的客户端。",
"addToGroupResult": "已将 {count} 个客户端添加到 {name}。",
"removeFromGroup": "移除客户端…",
+ "selectAllMatching": "选择所有匹配的客户端",
+ "selectionLimit": "选择或排除的项目最多为 {count} 个。",
"removeFromGroupTitle": "从分组 “{name}” 移除客户端",
"removeFromGroupDesc": "选择要从此分组中移除的成员。客户端本身保留(使用 “删除分组中的客户端” 完全移除)。",
"removeFromGroupResult": "已从 {name} 移除 {count} 个客户端。",
diff --git a/internal/web/translation/zh-TW.json b/internal/web/translation/zh-TW.json
index a736e06b7..cea16fcde 100644
--- a/internal/web/translation/zh-TW.json
+++ b/internal/web/translation/zh-TW.json
@@ -1202,6 +1202,8 @@
"addToGroupEmpty": "沒有其他可加入的客戶端。",
"addToGroupResult": "已將 {count} 個客戶端加入 {name}。",
"removeFromGroup": "移除客戶端…",
+ "selectAllMatching": "選取所有相符的用戶端",
+ "selectionLimit": "選取或排除的項目最多為 {count} 個。",
"removeFromGroupTitle": "從群組「{name}」移除客戶端",
"removeFromGroupDesc": "選擇要從此群組移除的成員。客戶端本身保留(用「刪除群組中的客戶端」完全移除)。",
"removeFromGroupResult": "已從 {name} 移除 {count} 個客戶端。",
diff --git a/tools/openapigen/main.go b/tools/openapigen/main.go
index f40382268..fe35e4bb3 100644
--- a/tools/openapigen/main.go
+++ b/tools/openapigen/main.go
@@ -114,6 +114,11 @@ func run(root, outDir string) error {
"ClientPageResponse",
"AttachCandidate",
"AttachCandidatePage",
+ "GroupClientPage",
+ "GroupClientRow",
+ "GroupClientSelection",
+ "BulkDeleteResult",
+ "BulkDeleteReport",
"AttachSelectionResult",
"BulkAdjustResult",
"BulkAdjustReport",