ChannelsTable.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. import React, { useEffect, useState } from 'react';
  2. import { Button, Form, Label, Pagination, Popup, Table } from 'semantic-ui-react';
  3. import { Link } from 'react-router-dom';
  4. import { API, showError, showInfo, showNotice, showSuccess, timestamp2string } from '../helpers';
  5. import { CHANNEL_OPTIONS, ITEMS_PER_PAGE } from '../constants';
  6. import { renderGroup, renderNumber } from '../helpers/render';
  7. function renderTimestamp(timestamp) {
  8. return (
  9. <>
  10. {timestamp2string(timestamp)}
  11. </>
  12. );
  13. }
  14. let type2label = undefined;
  15. function renderType(type) {
  16. if (!type2label) {
  17. type2label = new Map;
  18. for (let i = 0; i < CHANNEL_OPTIONS.length; i++) {
  19. type2label[CHANNEL_OPTIONS[i].value] = CHANNEL_OPTIONS[i];
  20. }
  21. type2label[0] = { value: 0, text: '未知类型', color: 'grey' };
  22. }
  23. return <Label basic color={type2label[type].color}>{type2label[type].text}</Label>;
  24. }
  25. function renderBalance(type, balance) {
  26. switch (type) {
  27. case 1: // OpenAI
  28. return <span>${balance.toFixed(2)}</span>;
  29. case 4: // CloseAI
  30. return <span>¥{balance.toFixed(2)}</span>;
  31. case 8: // 自定义
  32. return <span>${balance.toFixed(2)}</span>;
  33. case 5: // OpenAI-SB
  34. return <span>¥{(balance / 10000).toFixed(2)}</span>;
  35. case 10: // AI Proxy
  36. return <span>{renderNumber(balance)}</span>;
  37. case 12: // API2GPT
  38. return <span>¥{balance.toFixed(2)}</span>;
  39. case 13: // AIGC2D
  40. return <span>{renderNumber(balance)}</span>;
  41. default:
  42. return <span>不支持</span>;
  43. }
  44. }
  45. const ChannelsTable = () => {
  46. const [channels, setChannels] = useState([]);
  47. const [loading, setLoading] = useState(true);
  48. const [activePage, setActivePage] = useState(1);
  49. const [searchKeyword, setSearchKeyword] = useState('');
  50. const [searching, setSearching] = useState(false);
  51. const [updatingBalance, setUpdatingBalance] = useState(false);
  52. const loadChannels = async (startIdx) => {
  53. const res = await API.get(`/api/channel/?p=${startIdx}`);
  54. const { success, message, data } = res.data;
  55. if (success) {
  56. if (startIdx === 0) {
  57. setChannels(data);
  58. } else {
  59. let newChannels = [...channels];
  60. newChannels.splice(startIdx * ITEMS_PER_PAGE, data.length, ...data);
  61. setChannels(newChannels);
  62. }
  63. } else {
  64. showError(message);
  65. }
  66. setLoading(false);
  67. };
  68. const onPaginationChange = (e, { activePage }) => {
  69. (async () => {
  70. if (activePage === Math.ceil(channels.length / ITEMS_PER_PAGE) + 1) {
  71. // In this case we have to load more data and then append them.
  72. await loadChannels(activePage - 1);
  73. }
  74. setActivePage(activePage);
  75. })();
  76. };
  77. const refresh = async () => {
  78. setLoading(true);
  79. await loadChannels(activePage - 1);
  80. };
  81. useEffect(() => {
  82. loadChannels(0)
  83. .then()
  84. .catch((reason) => {
  85. showError(reason);
  86. });
  87. }, []);
  88. const manageChannel = async (id, action, idx) => {
  89. let data = { id };
  90. let res;
  91. switch (action) {
  92. case 'delete':
  93. res = await API.delete(`/api/channel/${id}/`);
  94. break;
  95. case 'enable':
  96. data.status = 1;
  97. res = await API.put('/api/channel/', data);
  98. break;
  99. case 'disable':
  100. data.status = 2;
  101. res = await API.put('/api/channel/', data);
  102. break;
  103. }
  104. const { success, message } = res.data;
  105. if (success) {
  106. showSuccess('操作成功完成!');
  107. let channel = res.data.data;
  108. let newChannels = [...channels];
  109. let realIdx = (activePage - 1) * ITEMS_PER_PAGE + idx;
  110. if (action === 'delete') {
  111. newChannels[realIdx].deleted = true;
  112. } else {
  113. newChannels[realIdx].status = channel.status;
  114. }
  115. setChannels(newChannels);
  116. } else {
  117. showError(message);
  118. }
  119. };
  120. const renderStatus = (status) => {
  121. switch (status) {
  122. case 1:
  123. return <Label basic color='green'>已启用</Label>;
  124. case 2:
  125. return (
  126. <Label basic color='red'>
  127. 已禁用
  128. </Label>
  129. );
  130. default:
  131. return (
  132. <Label basic color='grey'>
  133. 未知状态
  134. </Label>
  135. );
  136. }
  137. };
  138. const renderResponseTime = (responseTime) => {
  139. let time = responseTime / 1000;
  140. time = time.toFixed(2) + ' 秒';
  141. if (responseTime === 0) {
  142. return <Label basic color='grey'>未测试</Label>;
  143. } else if (responseTime <= 1000) {
  144. return <Label basic color='green'>{time}</Label>;
  145. } else if (responseTime <= 3000) {
  146. return <Label basic color='olive'>{time}</Label>;
  147. } else if (responseTime <= 5000) {
  148. return <Label basic color='yellow'>{time}</Label>;
  149. } else {
  150. return <Label basic color='red'>{time}</Label>;
  151. }
  152. };
  153. const searchChannels = async () => {
  154. if (searchKeyword === '') {
  155. // if keyword is blank, load files instead.
  156. await loadChannels(0);
  157. setActivePage(1);
  158. return;
  159. }
  160. setSearching(true);
  161. const res = await API.get(`/api/channel/search?keyword=${searchKeyword}`);
  162. const { success, message, data } = res.data;
  163. if (success) {
  164. setChannels(data);
  165. setActivePage(1);
  166. } else {
  167. showError(message);
  168. }
  169. setSearching(false);
  170. };
  171. const testChannel = async (id, name, idx) => {
  172. const res = await API.get(`/api/channel/test/${id}/`);
  173. const { success, message, time } = res.data;
  174. if (success) {
  175. let newChannels = [...channels];
  176. let realIdx = (activePage - 1) * ITEMS_PER_PAGE + idx;
  177. newChannels[realIdx].response_time = time * 1000;
  178. newChannels[realIdx].test_time = Date.now() / 1000;
  179. setChannels(newChannels);
  180. showInfo(`通道 ${name} 测试成功,耗时 ${time.toFixed(2)} 秒。`);
  181. } else {
  182. showError(message);
  183. showNotice("当前版本测试是通过按照 OpenAI API 格式使用 gpt-3.5-turbo 模型进行非流式请求实现的,因此测试报错并不一定代表通道不可用,该功能后续会修复。")
  184. }
  185. };
  186. const testAllChannels = async () => {
  187. const res = await API.get(`/api/channel/test`);
  188. const { success, message } = res.data;
  189. if (success) {
  190. showInfo('已成功开始测试所有已启用通道,请刷新页面查看结果。');
  191. } else {
  192. showError(message);
  193. }
  194. };
  195. const updateChannelBalance = async (id, name, idx) => {
  196. const res = await API.get(`/api/channel/update_balance/${id}/`);
  197. const { success, message, balance } = res.data;
  198. if (success) {
  199. let newChannels = [...channels];
  200. let realIdx = (activePage - 1) * ITEMS_PER_PAGE + idx;
  201. newChannels[realIdx].balance = balance;
  202. newChannels[realIdx].balance_updated_time = Date.now() / 1000;
  203. setChannels(newChannels);
  204. showInfo(`通道 ${name} 余额更新成功!`);
  205. } else {
  206. showError(message);
  207. }
  208. };
  209. const updateAllChannelsBalance = async () => {
  210. setUpdatingBalance(true);
  211. const res = await API.get(`/api/channel/update_balance`);
  212. const { success, message } = res.data;
  213. if (success) {
  214. showInfo('已更新完毕所有已启用通道余额!');
  215. } else {
  216. showError(message);
  217. }
  218. setUpdatingBalance(false);
  219. };
  220. const handleKeywordChange = async (e, { value }) => {
  221. setSearchKeyword(value.trim());
  222. };
  223. const sortChannel = (key) => {
  224. if (channels.length === 0) return;
  225. setLoading(true);
  226. let sortedChannels = [...channels];
  227. if (typeof sortedChannels[0][key] === 'string') {
  228. sortedChannels.sort((a, b) => {
  229. return ('' + a[key]).localeCompare(b[key]);
  230. });
  231. } else {
  232. sortedChannels.sort((a, b) => {
  233. if (a[key] === b[key]) return 0;
  234. if (a[key] > b[key]) return -1;
  235. if (a[key] < b[key]) return 1;
  236. });
  237. }
  238. if (sortedChannels[0].id === channels[0].id) {
  239. sortedChannels.reverse();
  240. }
  241. setChannels(sortedChannels);
  242. setLoading(false);
  243. };
  244. return (
  245. <>
  246. <Form onSubmit={searchChannels}>
  247. <Form.Input
  248. icon='search'
  249. fluid
  250. iconPosition='left'
  251. placeholder='搜索渠道的 ID,名称和密钥 ...'
  252. value={searchKeyword}
  253. loading={searching}
  254. onChange={handleKeywordChange}
  255. />
  256. </Form>
  257. <Table basic compact size='small'>
  258. <Table.Header>
  259. <Table.Row>
  260. <Table.HeaderCell
  261. style={{ cursor: 'pointer' }}
  262. onClick={() => {
  263. sortChannel('id');
  264. }}
  265. >
  266. ID
  267. </Table.HeaderCell>
  268. <Table.HeaderCell
  269. style={{ cursor: 'pointer' }}
  270. onClick={() => {
  271. sortChannel('name');
  272. }}
  273. >
  274. 名称
  275. </Table.HeaderCell>
  276. <Table.HeaderCell
  277. style={{ cursor: 'pointer' }}
  278. onClick={() => {
  279. sortChannel('group');
  280. }}
  281. >
  282. 分组
  283. </Table.HeaderCell>
  284. <Table.HeaderCell
  285. style={{ cursor: 'pointer' }}
  286. onClick={() => {
  287. sortChannel('type');
  288. }}
  289. >
  290. 类型
  291. </Table.HeaderCell>
  292. <Table.HeaderCell
  293. style={{ cursor: 'pointer' }}
  294. onClick={() => {
  295. sortChannel('status');
  296. }}
  297. >
  298. 状态
  299. </Table.HeaderCell>
  300. <Table.HeaderCell
  301. style={{ cursor: 'pointer' }}
  302. onClick={() => {
  303. sortChannel('response_time');
  304. }}
  305. >
  306. 响应时间
  307. </Table.HeaderCell>
  308. <Table.HeaderCell
  309. style={{ cursor: 'pointer' }}
  310. onClick={() => {
  311. sortChannel('balance');
  312. }}
  313. >
  314. 余额
  315. </Table.HeaderCell>
  316. <Table.HeaderCell>操作</Table.HeaderCell>
  317. </Table.Row>
  318. </Table.Header>
  319. <Table.Body>
  320. {channels
  321. .slice(
  322. (activePage - 1) * ITEMS_PER_PAGE,
  323. activePage * ITEMS_PER_PAGE
  324. )
  325. .map((channel, idx) => {
  326. if (channel.deleted) return <></>;
  327. return (
  328. <Table.Row key={channel.id}>
  329. <Table.Cell>{channel.id}</Table.Cell>
  330. <Table.Cell>{channel.name ? channel.name : '无'}</Table.Cell>
  331. <Table.Cell>{renderGroup(channel.group)}</Table.Cell>
  332. <Table.Cell>{renderType(channel.type)}</Table.Cell>
  333. <Table.Cell>{renderStatus(channel.status)}</Table.Cell>
  334. <Table.Cell>
  335. <Popup
  336. content={channel.test_time ? renderTimestamp(channel.test_time) : '未测试'}
  337. key={channel.id}
  338. trigger={renderResponseTime(channel.response_time)}
  339. basic
  340. />
  341. </Table.Cell>
  342. <Table.Cell>
  343. <Popup
  344. trigger={<span onClick={() => {
  345. updateChannelBalance(channel.id, channel.name, idx);
  346. }} style={{ cursor: 'pointer' }}>
  347. {renderBalance(channel.type, channel.balance)}
  348. </span>}
  349. content='点击更新'
  350. basic
  351. />
  352. </Table.Cell>
  353. <Table.Cell>
  354. <div>
  355. <Button
  356. size={'small'}
  357. positive
  358. onClick={() => {
  359. testChannel(channel.id, channel.name, idx);
  360. }}
  361. >
  362. 测试
  363. </Button>
  364. {/*<Button*/}
  365. {/* size={'small'}*/}
  366. {/* positive*/}
  367. {/* loading={updatingBalance}*/}
  368. {/* onClick={() => {*/}
  369. {/* updateChannelBalance(channel.id, channel.name, idx);*/}
  370. {/* }}*/}
  371. {/*>*/}
  372. {/* 更新余额*/}
  373. {/*</Button>*/}
  374. <Popup
  375. trigger={
  376. <Button size='small' negative>
  377. 删除
  378. </Button>
  379. }
  380. on='click'
  381. flowing
  382. hoverable
  383. >
  384. <Button
  385. negative
  386. onClick={() => {
  387. manageChannel(channel.id, 'delete', idx);
  388. }}
  389. >
  390. 删除渠道 {channel.name}
  391. </Button>
  392. </Popup>
  393. <Button
  394. size={'small'}
  395. onClick={() => {
  396. manageChannel(
  397. channel.id,
  398. channel.status === 1 ? 'disable' : 'enable',
  399. idx
  400. );
  401. }}
  402. >
  403. {channel.status === 1 ? '禁用' : '启用'}
  404. </Button>
  405. <Button
  406. size={'small'}
  407. as={Link}
  408. to={'/channel/edit/' + channel.id}
  409. >
  410. 编辑
  411. </Button>
  412. </div>
  413. </Table.Cell>
  414. </Table.Row>
  415. );
  416. })}
  417. </Table.Body>
  418. <Table.Footer>
  419. <Table.Row>
  420. <Table.HeaderCell colSpan='8'>
  421. <Button size='small' as={Link} to='/channel/add' loading={loading}>
  422. 添加新的渠道
  423. </Button>
  424. <Button size='small' loading={loading} onClick={testAllChannels}>
  425. 测试所有已启用通道
  426. </Button>
  427. <Button size='small' onClick={updateAllChannelsBalance}
  428. loading={loading || updatingBalance}>更新所有已启用通道余额</Button>
  429. <Pagination
  430. floated='right'
  431. activePage={activePage}
  432. onPageChange={onPaginationChange}
  433. size='small'
  434. siblingRange={1}
  435. totalPages={
  436. Math.ceil(channels.length / ITEMS_PER_PAGE) +
  437. (channels.length % ITEMS_PER_PAGE === 0 ? 1 : 0)
  438. }
  439. />
  440. <Button size='small' onClick={refresh} loading={loading}>刷新</Button>
  441. </Table.HeaderCell>
  442. </Table.Row>
  443. </Table.Footer>
  444. </Table>
  445. </>
  446. );
  447. };
  448. export default ChannelsTable;