TokensTable.js 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. import React, { useEffect, useState } from 'react';
  2. import { Button, Form, Label, Modal, 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. function renderTimestamp(timestamp) {
  7. return (
  8. <>
  9. {timestamp2string(timestamp)}
  10. </>
  11. );
  12. }
  13. function renderStatus(status) {
  14. switch (status) {
  15. case 1:
  16. return <Label basic color='green'>已启用</Label>;
  17. case 2:
  18. return <Label basic color='red'> 已禁用 </Label>;
  19. case 3:
  20. return <Label basic color='yellow'> 已过期 </Label>;
  21. case 4:
  22. return <Label basic color='grey'> 已耗尽 </Label>;
  23. default:
  24. return <Label basic color='black'> 未知状态 </Label>;
  25. }
  26. }
  27. const TokensTable = () => {
  28. const [tokens, setTokens] = useState([]);
  29. const [loading, setLoading] = useState(true);
  30. const [activePage, setActivePage] = useState(1);
  31. const [searchKeyword, setSearchKeyword] = useState('');
  32. const [searching, setSearching] = useState(false);
  33. const [showTopUpModal, setShowTopUpModal] = useState(false);
  34. const [targetTokenIdx, setTargetTokenIdx] = useState(0);
  35. const loadTokens = async (startIdx) => {
  36. const res = await API.get(`/api/token/?p=${startIdx}`);
  37. const { success, message, data } = res.data;
  38. if (success) {
  39. if (startIdx === 0) {
  40. setTokens(data);
  41. } else {
  42. let newTokens = tokens;
  43. newTokens.push(...data);
  44. setTokens(newTokens);
  45. }
  46. } else {
  47. showError(message);
  48. }
  49. setLoading(false);
  50. };
  51. const onPaginationChange = (e, { activePage }) => {
  52. (async () => {
  53. if (activePage === Math.ceil(tokens.length / ITEMS_PER_PAGE) + 1) {
  54. // In this case we have to load more data and then append them.
  55. await loadTokens(activePage - 1);
  56. }
  57. setActivePage(activePage);
  58. })();
  59. };
  60. const refresh = async () => {
  61. setLoading(true);
  62. await loadTokens(0);
  63. }
  64. useEffect(() => {
  65. loadTokens(0)
  66. .then()
  67. .catch((reason) => {
  68. showError(reason);
  69. });
  70. }, []);
  71. const manageToken = async (id, action, idx) => {
  72. let data = { id };
  73. let res;
  74. switch (action) {
  75. case 'delete':
  76. res = await API.delete(`/api/token/${id}/`);
  77. break;
  78. case 'enable':
  79. data.status = 1;
  80. res = await API.put('/api/token/?status_only=true', data);
  81. break;
  82. case 'disable':
  83. data.status = 2;
  84. res = await API.put('/api/token/?status_only=true', data);
  85. break;
  86. }
  87. const { success, message } = res.data;
  88. if (success) {
  89. showSuccess('操作成功完成!');
  90. let token = res.data.data;
  91. let newTokens = [...tokens];
  92. let realIdx = (activePage - 1) * ITEMS_PER_PAGE + idx;
  93. if (action === 'delete') {
  94. newTokens[realIdx].deleted = true;
  95. } else {
  96. newTokens[realIdx].status = token.status;
  97. }
  98. setTokens(newTokens);
  99. } else {
  100. showError(message);
  101. }
  102. };
  103. const searchTokens = async () => {
  104. if (searchKeyword === '') {
  105. // if keyword is blank, load files instead.
  106. await loadTokens(0);
  107. setActivePage(1);
  108. return;
  109. }
  110. setSearching(true);
  111. const res = await API.get(`/api/token/search?keyword=${searchKeyword}`);
  112. const { success, message, data } = res.data;
  113. if (success) {
  114. setTokens(data);
  115. setActivePage(1);
  116. } else {
  117. showError(message);
  118. }
  119. setSearching(false);
  120. };
  121. const handleKeywordChange = async (e, { value }) => {
  122. setSearchKeyword(value.trim());
  123. };
  124. const sortToken = (key) => {
  125. if (tokens.length === 0) return;
  126. setLoading(true);
  127. let sortedTokens = [...tokens];
  128. sortedTokens.sort((a, b) => {
  129. return ('' + a[key]).localeCompare(b[key]);
  130. });
  131. if (sortedTokens[0].id === tokens[0].id) {
  132. sortedTokens.reverse();
  133. }
  134. setTokens(sortedTokens);
  135. setLoading(false);
  136. };
  137. return (
  138. <>
  139. <Form onSubmit={searchTokens}>
  140. <Form.Input
  141. icon='search'
  142. fluid
  143. iconPosition='left'
  144. placeholder='搜索令牌的 ID 和名称 ...'
  145. value={searchKeyword}
  146. loading={searching}
  147. onChange={handleKeywordChange}
  148. />
  149. </Form>
  150. <Table basic>
  151. <Table.Header>
  152. <Table.Row>
  153. <Table.HeaderCell
  154. style={{ cursor: 'pointer' }}
  155. onClick={() => {
  156. sortToken('id');
  157. }}
  158. >
  159. ID
  160. </Table.HeaderCell>
  161. <Table.HeaderCell
  162. style={{ cursor: 'pointer' }}
  163. onClick={() => {
  164. sortToken('name');
  165. }}
  166. >
  167. 名称
  168. </Table.HeaderCell>
  169. <Table.HeaderCell
  170. style={{ cursor: 'pointer' }}
  171. onClick={() => {
  172. sortToken('status');
  173. }}
  174. >
  175. 状态
  176. </Table.HeaderCell>
  177. <Table.HeaderCell
  178. style={{ cursor: 'pointer' }}
  179. onClick={() => {
  180. sortToken('remain_quota');
  181. }}
  182. >
  183. 额度
  184. </Table.HeaderCell>
  185. <Table.HeaderCell
  186. style={{ cursor: 'pointer' }}
  187. onClick={() => {
  188. sortToken('created_time');
  189. }}
  190. >
  191. 创建时间
  192. </Table.HeaderCell>
  193. <Table.HeaderCell
  194. style={{ cursor: 'pointer' }}
  195. onClick={() => {
  196. sortToken('expired_time');
  197. }}
  198. >
  199. 过期时间
  200. </Table.HeaderCell>
  201. <Table.HeaderCell>操作</Table.HeaderCell>
  202. </Table.Row>
  203. </Table.Header>
  204. <Table.Body>
  205. {tokens
  206. .slice(
  207. (activePage - 1) * ITEMS_PER_PAGE,
  208. activePage * ITEMS_PER_PAGE
  209. )
  210. .map((token, idx) => {
  211. if (token.deleted) return <></>;
  212. return (
  213. <Table.Row key={token.id}>
  214. <Table.Cell>{token.id}</Table.Cell>
  215. <Table.Cell>{token.name ? token.name : '无'}</Table.Cell>
  216. <Table.Cell>{renderStatus(token.status)}</Table.Cell>
  217. <Table.Cell>{token.unlimited_quota ? '无限制' : token.remain_quota}</Table.Cell>
  218. <Table.Cell>{renderTimestamp(token.created_time)}</Table.Cell>
  219. <Table.Cell>{token.expired_time === -1 ? '永不过期' : renderTimestamp(token.expired_time)}</Table.Cell>
  220. <Table.Cell>
  221. <div>
  222. <Button
  223. size={'small'}
  224. positive
  225. onClick={async () => {
  226. let key = "sk-" + token.key;
  227. if (await copy(key)) {
  228. showSuccess('已复制到剪贴板!');
  229. } else {
  230. showWarning('无法复制到剪贴板,请手动复制,已将令牌填入搜索框。');
  231. setSearchKeyword(key);
  232. }
  233. }}
  234. >
  235. 复制
  236. </Button>
  237. <Popup
  238. trigger={
  239. <Button size='small' negative>
  240. 删除
  241. </Button>
  242. }
  243. on='click'
  244. flowing
  245. hoverable
  246. >
  247. <Button
  248. negative
  249. onClick={() => {
  250. manageToken(token.id, 'delete', idx);
  251. }}
  252. >
  253. 删除令牌 {token.name}
  254. </Button>
  255. </Popup>
  256. <Button
  257. size={'small'}
  258. onClick={() => {
  259. manageToken(
  260. token.id,
  261. token.status === 1 ? 'disable' : 'enable',
  262. idx
  263. );
  264. }}
  265. >
  266. {token.status === 1 ? '禁用' : '启用'}
  267. </Button>
  268. <Button
  269. size={'small'}
  270. as={Link}
  271. to={'/token/edit/' + token.id}
  272. >
  273. 编辑
  274. </Button>
  275. </div>
  276. </Table.Cell>
  277. </Table.Row>
  278. );
  279. })}
  280. </Table.Body>
  281. <Table.Footer>
  282. <Table.Row>
  283. <Table.HeaderCell colSpan='8'>
  284. <Button size='small' as={Link} to='/token/add' loading={loading}>
  285. 添加新的令牌
  286. </Button>
  287. <Button size='small' onClick={refresh} loading={loading}>刷新</Button>
  288. <Pagination
  289. floated='right'
  290. activePage={activePage}
  291. onPageChange={onPaginationChange}
  292. size='small'
  293. siblingRange={1}
  294. totalPages={
  295. Math.ceil(tokens.length / ITEMS_PER_PAGE) +
  296. (tokens.length % ITEMS_PER_PAGE === 0 ? 1 : 0)
  297. }
  298. />
  299. </Table.HeaderCell>
  300. </Table.Row>
  301. </Table.Footer>
  302. </Table>
  303. </>
  304. );
  305. };
  306. export default TokensTable;