Files
new-api/web/src/components/TokensTable.js

675 lines
17 KiB
JavaScript
Raw Normal View History

2024-03-15 16:05:33 +08:00
import React, { useEffect, useState } from 'react';
2024-03-23 21:24:39 +08:00
import {
API,
copy,
showError,
showSuccess,
timestamp2string,
} from '../helpers';
2024-03-15 16:05:33 +08:00
import { ITEMS_PER_PAGE } from '../constants';
2024-09-18 05:19:10 +08:00
import {renderGroup, renderQuota} from '../helpers/render';
2024-03-23 21:24:39 +08:00
import {
Button,
Dropdown,
Form,
Modal,
Popconfirm,
2024-09-18 05:19:10 +08:00
Popover, Space,
2024-03-23 21:24:39 +08:00
SplitButtonGroup,
Table,
Tag,
} from '@douyinfe/semi-ui';
2024-03-15 16:05:33 +08:00
import { IconTreeTriangleDown } from '@douyinfe/semi-icons';
import EditToken from '../pages/Token/EditToken';
const COPY_OPTIONS = [
2024-03-15 16:05:33 +08:00
{ key: 'next', text: 'ChatGPT Next Web', value: 'next' },
{ key: 'ama', text: 'ChatGPT Web & Midjourney', value: 'ama' },
2024-03-23 21:24:39 +08:00
{ key: 'opencat', text: 'OpenCat', value: 'opencat' },
];
const OPEN_LINK_OPTIONS = [
2024-03-15 16:05:33 +08:00
{ key: 'ama', text: 'ChatGPT Web & Midjourney', value: 'ama' },
2024-03-23 21:24:39 +08:00
{ key: 'opencat', text: 'OpenCat', value: 'opencat' },
];
2023-04-23 12:43:10 +08:00
function renderTimestamp(timestamp) {
2024-03-23 21:24:39 +08:00
return <>{timestamp2string(timestamp)}</>;
2023-04-23 11:31:00 +08:00
}
function renderStatus(status, model_limits_enabled = false) {
2024-03-15 16:05:33 +08:00
switch (status) {
case 1:
if (model_limits_enabled) {
2024-03-23 21:24:39 +08:00
return (
<Tag color='green' size='large'>
已启用限制模型
</Tag>
);
2024-03-15 16:05:33 +08:00
} else {
2024-03-23 21:24:39 +08:00
return (
<Tag color='green' size='large'>
已启用
</Tag>
);
2024-03-15 16:05:33 +08:00
}
case 2:
2024-03-23 21:24:39 +08:00
return (
<Tag color='red' size='large'>
{' '}
已禁用{' '}
</Tag>
);
2024-03-15 16:05:33 +08:00
case 3:
2024-03-23 21:24:39 +08:00
return (
<Tag color='yellow' size='large'>
{' '}
已过期{' '}
</Tag>
);
2024-03-15 16:05:33 +08:00
case 4:
2024-03-23 21:24:39 +08:00
return (
<Tag color='grey' size='large'>
{' '}
已耗尽{' '}
</Tag>
);
2024-03-15 16:05:33 +08:00
default:
2024-03-23 21:24:39 +08:00
return (
<Tag color='black' size='large'>
{' '}
未知状态{' '}
</Tag>
);
2024-03-15 16:05:33 +08:00
}
}
2023-04-23 11:31:00 +08:00
const TokensTable = () => {
2024-03-15 16:05:33 +08:00
const link_menu = [
{
2024-03-23 21:24:39 +08:00
node: 'item',
key: 'next',
name: 'ChatGPT Next Web',
onClick: () => {
2024-03-15 16:05:33 +08:00
onOpenLink('next');
2024-03-23 21:24:39 +08:00
},
2024-03-15 16:05:33 +08:00
},
{ node: 'item', key: 'ama', name: 'AMA 问天', value: 'ama' },
{
2024-03-23 21:24:39 +08:00
node: 'item',
key: 'next-mj',
name: 'ChatGPT Web & Midjourney',
value: 'next-mj',
onClick: () => {
2024-03-15 16:05:33 +08:00
onOpenLink('next-mj');
2024-03-23 21:24:39 +08:00
},
2024-03-15 16:05:33 +08:00
},
2024-03-23 21:24:39 +08:00
{ node: 'item', key: 'opencat', name: 'OpenCat', value: 'opencat' },
2024-03-15 16:05:33 +08:00
];
const columns = [
{
title: '名称',
2024-03-23 21:24:39 +08:00
dataIndex: 'name',
2024-03-15 16:05:33 +08:00
},
{
title: '状态',
dataIndex: 'status',
key: 'status',
render: (text, record, index) => {
2024-09-18 05:19:10 +08:00
return <div>
<Space>
{renderStatus(text, record.model_limits_enabled)}
{renderGroup(record.group)}
</Space>
</div>;
2024-03-23 21:24:39 +08:00
},
2024-03-15 16:05:33 +08:00
},
{
title: '已用额度',
dataIndex: 'used_quota',
render: (text, record, index) => {
2024-03-23 21:24:39 +08:00
return <div>{renderQuota(parseInt(text))}</div>;
},
2024-03-15 16:05:33 +08:00
},
{
title: '剩余额度',
dataIndex: 'remain_quota',
render: (text, record, index) => {
return (
<div>
2024-03-23 21:24:39 +08:00
{record.unlimited_quota ? (
<Tag size={'large'} color={'white'}>
无限制
</Tag>
) : (
<Tag size={'large'} color={'light-blue'}>
{renderQuota(parseInt(text))}
</Tag>
)}
2024-03-15 16:05:33 +08:00
</div>
);
2024-03-23 21:24:39 +08:00
},
2024-03-15 16:05:33 +08:00
},
{
title: '创建时间',
dataIndex: 'created_time',
render: (text, record, index) => {
2024-03-23 21:24:39 +08:00
return <div>{renderTimestamp(text)}</div>;
},
2024-03-15 16:05:33 +08:00
},
{
title: '过期时间',
dataIndex: 'expired_time',
render: (text, record, index) => {
return (
<div>
{record.expired_time === -1 ? '永不过期' : renderTimestamp(text)}
</div>
);
2024-03-23 21:24:39 +08:00
},
2024-03-15 16:05:33 +08:00
},
{
title: '',
dataIndex: 'operate',
render: (text, record, index) => (
<div>
<Popover
2024-03-23 21:24:39 +08:00
content={'sk-' + record.key}
2024-03-15 16:05:33 +08:00
style={{ padding: 20 }}
2024-03-23 21:24:39 +08:00
position='top'
2024-03-15 16:05:33 +08:00
>
2024-03-23 21:24:39 +08:00
<Button theme='light' type='tertiary' style={{ marginRight: 1 }}>
查看
</Button>
2024-03-15 16:05:33 +08:00
</Popover>
2024-03-23 21:24:39 +08:00
<Button
theme='light'
type='secondary'
style={{ marginRight: 1 }}
onClick={async (text) => {
await copyText('sk-' + record.key);
}}
>
复制
</Button>
<SplitButtonGroup
style={{ marginRight: 1 }}
aria-label='项目操作按钮组'
>
<Button
theme='light'
style={{ color: 'rgba(var(--semi-teal-7), 1)' }}
onClick={() => {
onOpenLink('next', record.key);
}}
>
聊天
</Button>
<Dropdown
trigger='click'
position='bottomRight'
menu={[
2024-03-15 16:05:33 +08:00
{
node: 'item',
key: 'next',
disabled: !localStorage.getItem('chat_link'),
name: 'ChatGPT Next Web',
onClick: () => {
onOpenLink('next', record.key);
2024-03-23 21:24:39 +08:00
},
2024-03-15 16:05:33 +08:00
},
{
node: 'item',
key: 'next-mj',
disabled: !localStorage.getItem('chat_link2'),
name: 'ChatGPT Web & Midjourney',
onClick: () => {
onOpenLink('next-mj', record.key);
2024-03-23 21:24:39 +08:00
},
2024-03-15 16:05:33 +08:00
},
2024-09-05 18:34:04 +08:00
// {
// node: 'item',
// key: 'lobe',
// name: 'Lobe Chat',
// onClick: () => {
// onOpenLink('lobe', record.key);
// },
// },
2024-03-15 16:05:33 +08:00
{
2024-03-23 21:24:39 +08:00
node: 'item',
key: 'ama',
name: 'AMA 问天BotGem',
onClick: () => {
2024-03-15 16:05:33 +08:00
onOpenLink('ama', record.key);
2024-03-23 21:24:39 +08:00
},
2024-03-15 16:05:33 +08:00
},
{
2024-03-23 21:24:39 +08:00
node: 'item',
key: 'opencat',
name: 'OpenCat',
onClick: () => {
2024-03-15 16:05:33 +08:00
onOpenLink('opencat', record.key);
2024-03-23 21:24:39 +08:00
},
},
]}
2024-03-15 16:05:33 +08:00
>
2024-03-23 21:24:39 +08:00
<Button
style={{
padding: '8px 4px',
color: 'rgba(var(--semi-teal-7), 1)',
}}
type='primary'
icon={<IconTreeTriangleDown />}
></Button>
2024-03-15 16:05:33 +08:00
</Dropdown>
</SplitButtonGroup>
<Popconfirm
2024-03-23 21:24:39 +08:00
title='确定是否要删除此令牌?'
content='此修改将不可逆'
2024-03-15 16:05:33 +08:00
okType={'danger'}
position={'left'}
onConfirm={() => {
2024-03-23 21:24:39 +08:00
manageToken(record.id, 'delete', record).then(() => {
removeRecord(record.key);
});
2024-03-15 16:05:33 +08:00
}}
>
2024-03-23 21:24:39 +08:00
<Button theme='light' type='danger' style={{ marginRight: 1 }}>
删除
</Button>
2024-03-15 16:05:33 +08:00
</Popconfirm>
2024-03-23 21:24:39 +08:00
{record.status === 1 ? (
<Button
theme='light'
type='warning'
style={{ marginRight: 1 }}
onClick={async () => {
manageToken(record.id, 'disable', record);
}}
>
禁用
</Button>
) : (
<Button
theme='light'
type='secondary'
style={{ marginRight: 1 }}
onClick={async () => {
manageToken(record.id, 'enable', record);
}}
>
启用
</Button>
)}
<Button
theme='light'
type='tertiary'
style={{ marginRight: 1 }}
onClick={() => {
2024-03-15 16:05:33 +08:00
setEditingToken(record);
setShowEdit(true);
2024-03-23 21:24:39 +08:00
}}
>
编辑
</Button>
2024-03-15 16:05:33 +08:00
</div>
2024-03-23 21:24:39 +08:00
),
},
2024-03-15 16:05:33 +08:00
];
const [pageSize, setPageSize] = useState(ITEMS_PER_PAGE);
const [showEdit, setShowEdit] = useState(false);
const [tokens, setTokens] = useState([]);
const [selectedKeys, setSelectedKeys] = useState([]);
const [tokenCount, setTokenCount] = useState(pageSize);
const [loading, setLoading] = useState(true);
const [activePage, setActivePage] = useState(1);
const [searchKeyword, setSearchKeyword] = useState('');
const [searchToken, setSearchToken] = useState('');
const [searching, setSearching] = useState(false);
const [showTopUpModal, setShowTopUpModal] = useState(false);
const [targetTokenIdx, setTargetTokenIdx] = useState(0);
const [editingToken, setEditingToken] = useState({
2024-03-23 21:24:39 +08:00
id: undefined,
2024-03-15 16:05:33 +08:00
});
const closeEdit = () => {
setShowEdit(false);
setTimeout(() => {
setEditingToken({
2024-03-23 21:24:39 +08:00
id: undefined,
2024-03-15 16:05:33 +08:00
});
}, 500);
};
const setTokensFormat = (tokens) => {
setTokens(tokens);
if (tokens.length >= pageSize) {
setTokenCount(tokens.length + pageSize);
} else {
setTokenCount(tokens.length);
}
};
2024-03-23 21:24:39 +08:00
let pageData = tokens.slice(
(activePage - 1) * pageSize,
activePage * pageSize,
);
2024-03-15 16:05:33 +08:00
const loadTokens = async (startIdx) => {
setLoading(true);
const res = await API.get(`/api/token/?p=${startIdx}&size=${pageSize}`);
const { success, message, data } = res.data;
if (success) {
if (startIdx === 0) {
setTokensFormat(data);
} else {
let newTokens = [...tokens];
newTokens.splice(startIdx * pageSize, data.length, ...data);
setTokensFormat(newTokens);
}
} else {
showError(message);
}
setLoading(false);
};
2023-10-31 22:41:34 +08:00
2024-03-15 16:05:33 +08:00
const onPaginationChange = (e, { activePage }) => {
(async () => {
if (activePage === Math.ceil(tokens.length / pageSize) + 1) {
// In this case we have to load more data and then append them.
2023-04-23 12:43:10 +08:00
await loadTokens(activePage - 1);
2024-03-15 16:05:33 +08:00
}
setActivePage(activePage);
})();
};
const refresh = async () => {
await loadTokens(activePage - 1);
};
const copyText = async (text) => {
if (await copy(text)) {
showSuccess('已复制到剪贴板!');
} else {
2024-03-25 16:49:53 +08:00
Modal.error({
title: '无法复制到剪贴板,请手动复制',
content: text,
size: 'large',
});
2024-03-15 16:05:33 +08:00
}
};
const onOpenLink = async (type, key) => {
let status = localStorage.getItem('status');
let serverAddress = '';
if (status) {
status = JSON.parse(status);
serverAddress = status.server_address;
}
if (serverAddress === '') {
serverAddress = window.location.origin;
}
let encodedServerAddress = encodeURIComponent(serverAddress);
const chatLink = localStorage.getItem('chat_link');
const mjLink = localStorage.getItem('chat_link2');
let defaultUrl;
2023-10-31 22:41:34 +08:00
2024-03-15 16:05:33 +08:00
if (chatLink) {
2024-03-23 21:24:39 +08:00
defaultUrl =
chatLink + `/#/?settings={"key":"sk-${key}","url":"${serverAddress}"}`;
2024-03-15 16:05:33 +08:00
}
let url;
switch (type) {
case 'ama':
url = `ama://set-api-key?server=${encodedServerAddress}&key=sk-${key}`;
break;
case 'opencat':
url = `opencat://team/join?domain=${encodedServerAddress}&token=sk-${key}`;
break;
case 'lobe':
2024-08-16 14:59:32 +08:00
url = `https://chat-preview.lobehub.com/?settings={"keyVaults":{"openai":{"apiKey":"sk-${key}","baseURL":"${encodedServerAddress}/v1"}}}`;
break;
2024-03-15 16:05:33 +08:00
case 'next-mj':
2024-03-23 21:24:39 +08:00
url =
mjLink + `/#/?settings={"key":"sk-${key}","url":"${serverAddress}"}`;
2024-03-15 16:05:33 +08:00
break;
default:
if (!chatLink) {
showError('管理员未设置聊天链接');
return;
2023-10-31 22:41:34 +08:00
}
2024-03-15 16:05:33 +08:00
url = defaultUrl;
}
2023-10-31 22:41:34 +08:00
2024-03-15 16:05:33 +08:00
window.open(url, '_blank');
};
useEffect(() => {
loadTokens(0)
.then()
.catch((reason) => {
showError(reason);
});
}, [pageSize]);
2024-03-23 21:24:39 +08:00
const removeRecord = (key) => {
2024-03-15 16:05:33 +08:00
let newDataSource = [...tokens];
if (key != null) {
2024-03-23 21:24:39 +08:00
let idx = newDataSource.findIndex((data) => data.key === key);
2024-03-15 16:05:33 +08:00
if (idx > -1) {
newDataSource.splice(idx, 1);
setTokensFormat(newDataSource);
}
2023-04-23 11:31:00 +08:00
}
2024-03-15 16:05:33 +08:00
};
const manageToken = async (id, action, record) => {
setLoading(true);
let data = { id };
let res;
switch (action) {
case 'delete':
res = await API.delete(`/api/token/${id}/`);
break;
case 'enable':
data.status = 1;
res = await API.put('/api/token/?status_only=true', data);
break;
case 'disable':
data.status = 2;
res = await API.put('/api/token/?status_only=true', data);
break;
}
const { success, message } = res.data;
if (success) {
showSuccess('操作成功完成!');
let token = res.data.data;
let newTokens = [...tokens];
// let realIdx = (activePage - 1) * ITEMS_PER_PAGE + idx;
if (action === 'delete') {
} else {
record.status = token.status;
// newTokens[realIdx].status = token.status;
}
setTokensFormat(newTokens);
} else {
showError(message);
}
setLoading(false);
};
const searchTokens = async () => {
if (searchKeyword === '' && searchToken === '') {
// if keyword is blank, load files instead.
await loadTokens(0);
setActivePage(1);
return;
}
setSearching(true);
2024-03-23 21:24:39 +08:00
const res = await API.get(
`/api/token/search?keyword=${searchKeyword}&token=${searchToken}`,
);
2024-03-15 16:05:33 +08:00
const { success, message, data } = res.data;
if (success) {
setTokensFormat(data);
setActivePage(1);
} else {
showError(message);
}
setSearching(false);
};
const handleKeywordChange = async (value) => {
setSearchKeyword(value.trim());
};
const handleSearchTokenChange = async (value) => {
setSearchToken(value.trim());
};
const sortToken = (key) => {
if (tokens.length === 0) return;
setLoading(true);
let sortedTokens = [...tokens];
sortedTokens.sort((a, b) => {
return ('' + a[key]).localeCompare(b[key]);
});
if (sortedTokens[0].id === tokens[0].id) {
sortedTokens.reverse();
}
setTokens(sortedTokens);
setLoading(false);
};
2023-10-31 22:41:34 +08:00
2024-03-23 21:24:39 +08:00
const handlePageChange = (page) => {
2024-03-15 16:05:33 +08:00
setActivePage(page);
if (page === Math.ceil(tokens.length / pageSize) + 1) {
// In this case we have to load more data and then append them.
2024-03-23 21:24:39 +08:00
loadTokens(page - 1).then((r) => {});
2024-03-15 16:05:33 +08:00
}
};
const rowSelection = {
2024-03-23 21:24:39 +08:00
onSelect: (record, selected) => {},
onSelectAll: (selected, selectedRows) => {},
2024-03-15 16:05:33 +08:00
onChange: (selectedRowKeys, selectedRows) => {
setSelectedKeys(selectedRows);
2024-03-23 21:24:39 +08:00
},
2024-03-15 16:05:33 +08:00
};
2023-10-31 22:41:34 +08:00
2024-03-15 16:05:33 +08:00
const handleRow = (record, index) => {
if (record.status !== 1) {
return {
style: {
2024-03-23 21:24:39 +08:00
background: 'var(--semi-color-disabled-border)',
},
2024-03-15 16:05:33 +08:00
};
} else {
return {};
}
};
return (
<>
2024-03-23 21:24:39 +08:00
<EditToken
refresh={refresh}
editingToken={editingToken}
visiable={showEdit}
handleClose={closeEdit}
></EditToken>
<Form
layout='horizontal'
style={{ marginTop: 10 }}
labelPosition={'left'}
>
2024-03-15 16:05:33 +08:00
<Form.Input
2024-03-23 21:24:39 +08:00
field='keyword'
label='搜索关键字'
placeholder='令牌名称'
2024-03-15 16:05:33 +08:00
value={searchKeyword}
loading={searching}
onChange={handleKeywordChange}
/>
<Form.Input
2024-03-23 21:24:39 +08:00
field='token'
label='Key'
placeholder='密钥'
2024-03-15 16:05:33 +08:00
value={searchToken}
loading={searching}
onChange={handleSearchTokenChange}
/>
2024-03-23 21:24:39 +08:00
<Button
label='查询'
type='primary'
htmlType='submit'
className='btn-margin-right'
onClick={searchTokens}
style={{ marginRight: 8 }}
>
查询
</Button>
2024-03-15 16:05:33 +08:00
</Form>
2024-03-23 21:24:39 +08:00
<Table
style={{ marginTop: 20 }}
columns={columns}
dataSource={pageData}
pagination={{
currentPage: activePage,
pageSize: pageSize,
total: tokenCount,
showSizeChanger: true,
pageSizeOptions: [10, 20, 50, 100],
formatPageText: (page) =>
`${page.currentStart} - ${page.currentEnd} 条,共 ${tokens.length}`,
onPageSizeChange: (size) => {
setPageSize(size);
setActivePage(1);
},
onPageChange: handlePageChange,
}}
loading={loading}
rowSelection={rowSelection}
onRow={handleRow}
></Table>
<Button
theme='light'
type='primary'
style={{ marginRight: 8 }}
onClick={() => {
2024-03-15 16:05:33 +08:00
setEditingToken({
2024-03-23 21:24:39 +08:00
id: undefined,
2024-03-15 16:05:33 +08:00
});
setShowEdit(true);
2024-03-23 21:24:39 +08:00
}}
>
添加令牌
</Button>
<Button
label='复制所选令牌'
type='warning'
onClick={async () => {
2024-03-15 16:05:33 +08:00
if (selectedKeys.length === 0) {
showError('请至少选择一个令牌!');
return;
}
let keys = '';
for (let i = 0; i < selectedKeys.length; i++) {
2024-03-23 21:24:39 +08:00
keys +=
selectedKeys[i].name + ' sk-' + selectedKeys[i].key + '\n';
2024-03-15 16:05:33 +08:00
}
await copyText(keys);
2024-03-23 21:24:39 +08:00
}}
>
复制所选令牌到剪贴板
</Button>
2024-03-15 16:05:33 +08:00
</>
);
2023-04-23 11:31:00 +08:00
};
export default TokensTable;