TokensTable.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. import React, { useEffect, useState } from 'react';
  2. import { Button, Dropdown, Form, Label, Pagination, Popup, Table } from 'semantic-ui-react';
  3. import { Link } from 'react-router-dom';
  4. import { API, copy, showError, showSuccess, showWarning, timestamp2string } from '../helpers';
  5. import { ITEMS_PER_PAGE } from '../constants';
  6. import { renderQuota } from '../helpers/render';
  7. const COPY_OPTIONS = [
  8. { key: 'next', text: 'ChatGPT Next Web', value: 'next' },
  9. { key: 'ama', text: 'AMA 问天', value: 'ama' },
  10. { key: 'opencat', text: 'OpenCat', value: 'opencat' },
  11. ];
  12. const OPEN_LINK_OPTIONS = [
  13. { key: 'ama', text: 'AMA 问天', value: 'ama' },
  14. { key: 'opencat', text: 'OpenCat', value: 'opencat' },
  15. ];
  16. function renderTimestamp(timestamp) {
  17. return (
  18. <>
  19. {timestamp2string(timestamp)}
  20. </>
  21. );
  22. }
  23. function renderStatus(status) {
  24. switch (status) {
  25. case 1:
  26. return <Label basic color='green'>已启用</Label>;
  27. case 2:
  28. return <Label basic color='red'> 已禁用 </Label>;
  29. case 3:
  30. return <Label basic color='yellow'> 已过期 </Label>;
  31. case 4:
  32. return <Label basic color='grey'> 已耗尽 </Label>;
  33. default:
  34. return <Label basic color='black'> 未知状态 </Label>;
  35. }
  36. }
  37. const TokensTable = () => {
  38. const [tokens, setTokens] = useState([]);
  39. const [loading, setLoading] = useState(true);
  40. const [activePage, setActivePage] = useState(1);
  41. const [searchKeyword, setSearchKeyword] = useState('');
  42. const [searching, setSearching] = useState(false);
  43. const [showTopUpModal, setShowTopUpModal] = useState(false);
  44. const [targetTokenIdx, setTargetTokenIdx] = useState(0);
  45. const loadTokens = async (startIdx) => {
  46. const res = await API.get(`/api/token/?p=${startIdx}`);
  47. const { success, message, data } = res.data;
  48. if (success) {
  49. if (startIdx === 0) {
  50. setTokens(data);
  51. } else {
  52. let newTokens = [...tokens];
  53. newTokens.splice(startIdx * ITEMS_PER_PAGE, data.length, ...data);
  54. setTokens(newTokens);
  55. }
  56. } else {
  57. showError(message);
  58. }
  59. setLoading(false);
  60. };
  61. const onPaginationChange = (e, { activePage }) => {
  62. (async () => {
  63. if (activePage === Math.ceil(tokens.length / ITEMS_PER_PAGE) + 1) {
  64. // In this case we have to load more data and then append them.
  65. await loadTokens(activePage - 1);
  66. }
  67. setActivePage(activePage);
  68. })();
  69. };
  70. const refresh = async () => {
  71. setLoading(true);
  72. await loadTokens(activePage - 1);
  73. };
  74. const onCopy = async (type, key) => {
  75. let status = localStorage.getItem('status');
  76. let serverAddress = '';
  77. if (status) {
  78. status = JSON.parse(status);
  79. serverAddress = status.server_address;
  80. }
  81. if (serverAddress === '') {
  82. serverAddress = window.location.origin;
  83. }
  84. let encodedServerAddress = encodeURIComponent(serverAddress);
  85. const nextLink = localStorage.getItem('chat_link');
  86. let nextUrl;
  87. if (nextLink) {
  88. nextUrl = nextLink + `/#/?settings={"key":"sk-${key}","url":"${serverAddress}"}`;
  89. } else {
  90. nextUrl = `https://chat.oneapi.pro/#/?settings={"key":"sk-${key}","url":"${serverAddress}"}`;
  91. }
  92. let url;
  93. switch (type) {
  94. case 'ama':
  95. url = `ama://set-api-key?server=${encodedServerAddress}&key=sk-${key}`;
  96. break;
  97. case 'opencat':
  98. url = `opencat://team/join?domain=${encodedServerAddress}&token=sk-${key}`;
  99. break;
  100. case 'next':
  101. url = nextUrl;
  102. break;
  103. default:
  104. url = `sk-${key}`;
  105. }
  106. if (await copy(url)) {
  107. showSuccess('已复制到剪贴板!');
  108. } else {
  109. showWarning('无法复制到剪贴板,请手动复制,已将令牌填入搜索框。');
  110. setSearchKeyword(url);
  111. }
  112. };
  113. const onOpenLink = async (type, key) => {
  114. let status = localStorage.getItem('status');
  115. let serverAddress = '';
  116. if (status) {
  117. status = JSON.parse(status);
  118. serverAddress = status.server_address;
  119. }
  120. if (serverAddress === '') {
  121. serverAddress = window.location.origin;
  122. }
  123. let encodedServerAddress = encodeURIComponent(serverAddress);
  124. const chatLink = localStorage.getItem('chat_link');
  125. let defaultUrl;
  126. if (chatLink) {
  127. defaultUrl = chatLink + `/#/?settings={"key":"sk-${key}","url":"${serverAddress}"}`;
  128. } else {
  129. defaultUrl = `https://chat.oneapi.pro/#/?settings={"key":"sk-${key}","url":"${serverAddress}"}`;
  130. }
  131. let url;
  132. switch (type) {
  133. case 'ama':
  134. url = `ama://set-api-key?server=${encodedServerAddress}&key=sk-${key}`;
  135. break;
  136. case 'opencat':
  137. url = `opencat://team/join?domain=${encodedServerAddress}&token=sk-${key}`;
  138. break;
  139. default:
  140. url = defaultUrl;
  141. }
  142. window.open(url, '_blank');
  143. }
  144. useEffect(() => {
  145. loadTokens(0)
  146. .then()
  147. .catch((reason) => {
  148. showError(reason);
  149. });
  150. }, []);
  151. const manageToken = async (id, action, idx) => {
  152. let data = { id };
  153. let res;
  154. switch (action) {
  155. case 'delete':
  156. res = await API.delete(`/api/token/${id}/`);
  157. break;
  158. case 'enable':
  159. data.status = 1;
  160. res = await API.put('/api/token/?status_only=true', data);
  161. break;
  162. case 'disable':
  163. data.status = 2;
  164. res = await API.put('/api/token/?status_only=true', data);
  165. break;
  166. }
  167. const { success, message } = res.data;
  168. if (success) {
  169. showSuccess('操作成功完成!');
  170. let token = res.data.data;
  171. let newTokens = [...tokens];
  172. let realIdx = (activePage - 1) * ITEMS_PER_PAGE + idx;
  173. if (action === 'delete') {
  174. newTokens[realIdx].deleted = true;
  175. } else {
  176. newTokens[realIdx].status = token.status;
  177. }
  178. setTokens(newTokens);
  179. } else {
  180. showError(message);
  181. }
  182. };
  183. const searchTokens = async () => {
  184. if (searchKeyword === '') {
  185. // if keyword is blank, load files instead.
  186. await loadTokens(0);
  187. setActivePage(1);
  188. return;
  189. }
  190. setSearching(true);
  191. const res = await API.get(`/api/token/search?keyword=${searchKeyword}`);
  192. const { success, message, data } = res.data;
  193. if (success) {
  194. setTokens(data);
  195. setActivePage(1);
  196. } else {
  197. showError(message);
  198. }
  199. setSearching(false);
  200. };
  201. const handleKeywordChange = async (e, { value }) => {
  202. setSearchKeyword(value.trim());
  203. };
  204. const sortToken = (key) => {
  205. if (tokens.length === 0) return;
  206. setLoading(true);
  207. let sortedTokens = [...tokens];
  208. sortedTokens.sort((a, b) => {
  209. return ('' + a[key]).localeCompare(b[key]);
  210. });
  211. if (sortedTokens[0].id === tokens[0].id) {
  212. sortedTokens.reverse();
  213. }
  214. setTokens(sortedTokens);
  215. setLoading(false);
  216. };
  217. return (
  218. <>
  219. <Form onSubmit={searchTokens}>
  220. <Form.Input
  221. icon='search'
  222. fluid
  223. iconPosition='left'
  224. placeholder='搜索令牌的名称 ...'
  225. value={searchKeyword}
  226. loading={searching}
  227. onChange={handleKeywordChange}
  228. />
  229. </Form>
  230. <Table basic compact size='small'>
  231. <Table.Header>
  232. <Table.Row>
  233. <Table.HeaderCell
  234. style={{ cursor: 'pointer' }}
  235. onClick={() => {
  236. sortToken('name');
  237. }}
  238. >
  239. 名称
  240. </Table.HeaderCell>
  241. <Table.HeaderCell
  242. style={{ cursor: 'pointer' }}
  243. onClick={() => {
  244. sortToken('status');
  245. }}
  246. >
  247. 状态
  248. </Table.HeaderCell>
  249. <Table.HeaderCell
  250. style={{ cursor: 'pointer' }}
  251. onClick={() => {
  252. sortToken('used_quota');
  253. }}
  254. >
  255. 已用额度
  256. </Table.HeaderCell>
  257. <Table.HeaderCell
  258. style={{ cursor: 'pointer' }}
  259. onClick={() => {
  260. sortToken('remain_quota');
  261. }}
  262. >
  263. 剩余额度
  264. </Table.HeaderCell>
  265. <Table.HeaderCell
  266. style={{ cursor: 'pointer' }}
  267. onClick={() => {
  268. sortToken('created_time');
  269. }}
  270. >
  271. 创建时间
  272. </Table.HeaderCell>
  273. <Table.HeaderCell
  274. style={{ cursor: 'pointer' }}
  275. onClick={() => {
  276. sortToken('expired_time');
  277. }}
  278. >
  279. 过期时间
  280. </Table.HeaderCell>
  281. <Table.HeaderCell>操作</Table.HeaderCell>
  282. </Table.Row>
  283. </Table.Header>
  284. <Table.Body>
  285. {tokens
  286. .slice(
  287. (activePage - 1) * ITEMS_PER_PAGE,
  288. activePage * ITEMS_PER_PAGE
  289. )
  290. .map((token, idx) => {
  291. if (token.deleted) return <></>;
  292. return (
  293. <Table.Row key={token.id}>
  294. <Table.Cell>{token.name ? token.name : '无'}</Table.Cell>
  295. <Table.Cell>{renderStatus(token.status)}</Table.Cell>
  296. <Table.Cell>{renderQuota(token.used_quota)}</Table.Cell>
  297. <Table.Cell>{token.unlimited_quota ? '无限制' : renderQuota(token.remain_quota, 2)}</Table.Cell>
  298. <Table.Cell>{renderTimestamp(token.created_time)}</Table.Cell>
  299. <Table.Cell>{token.expired_time === -1 ? '永不过期' : renderTimestamp(token.expired_time)}</Table.Cell>
  300. <Table.Cell>
  301. <div>
  302. <Button.Group color='green' size={'small'}>
  303. <Button
  304. size={'small'}
  305. positive
  306. onClick={async () => {
  307. await onCopy('', token.key);
  308. }}
  309. >
  310. 复制
  311. </Button>
  312. <Dropdown
  313. className='button icon'
  314. floating
  315. options={COPY_OPTIONS.map(option => ({
  316. ...option,
  317. onClick: async () => {
  318. await onCopy(option.value, token.key);
  319. }
  320. }))}
  321. trigger={<></>}
  322. />
  323. </Button.Group>
  324. {' '}
  325. <Button.Group color='blue' size={'small'}>
  326. <Button
  327. size={'small'}
  328. positive
  329. onClick={() => {
  330. onOpenLink('', token.key);
  331. }}>
  332. 聊天
  333. </Button>
  334. <Dropdown
  335. className="button icon"
  336. floating
  337. options={OPEN_LINK_OPTIONS.map(option => ({
  338. ...option,
  339. onClick: async () => {
  340. await onOpenLink(option.value, token.key);
  341. }
  342. }))}
  343. trigger={<></>}
  344. />
  345. </Button.Group>
  346. {' '}
  347. <Popup
  348. trigger={
  349. <Button size='small' negative>
  350. 删除
  351. </Button>
  352. }
  353. on='click'
  354. flowing
  355. hoverable
  356. >
  357. <Button
  358. negative
  359. onClick={() => {
  360. manageToken(token.id, 'delete', idx);
  361. }}
  362. >
  363. 删除令牌 {token.name}
  364. </Button>
  365. </Popup>
  366. <Button
  367. size={'small'}
  368. onClick={() => {
  369. manageToken(
  370. token.id,
  371. token.status === 1 ? 'disable' : 'enable',
  372. idx
  373. );
  374. }}
  375. >
  376. {token.status === 1 ? '禁用' : '启用'}
  377. </Button>
  378. <Button
  379. size={'small'}
  380. as={Link}
  381. to={'/token/edit/' + token.id}
  382. >
  383. 编辑
  384. </Button>
  385. </div>
  386. </Table.Cell>
  387. </Table.Row>
  388. );
  389. })}
  390. </Table.Body>
  391. <Table.Footer>
  392. <Table.Row>
  393. <Table.HeaderCell colSpan='7'>
  394. <Button size='small' as={Link} to='/token/add' loading={loading}>
  395. 添加新的令牌
  396. </Button>
  397. <Button size='small' onClick={refresh} loading={loading}>刷新</Button>
  398. <Pagination
  399. floated='right'
  400. activePage={activePage}
  401. onPageChange={onPaginationChange}
  402. size='small'
  403. siblingRange={1}
  404. totalPages={
  405. Math.ceil(tokens.length / ITEMS_PER_PAGE) +
  406. (tokens.length % ITEMS_PER_PAGE === 0 ? 1 : 0)
  407. }
  408. />
  409. </Table.HeaderCell>
  410. </Table.Row>
  411. </Table.Footer>
  412. </Table>
  413. </>
  414. );
  415. };
  416. export default TokensTable;