useTokensData.js 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. /*
  2. Copyright (C) 2025 QuantumNous
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU Affero General Public License as
  5. published by the Free Software Foundation, either version 3 of the
  6. License, or (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU Affero General Public License for more details.
  11. You should have received a copy of the GNU Affero General Public License
  12. along with this program. If not, see <https://www.gnu.org/licenses/>.
  13. For commercial licensing, please contact support@quantumnous.com
  14. */
  15. import { useState, useEffect } from 'react';
  16. import { useTranslation } from 'react-i18next';
  17. import { Modal } from '@douyinfe/semi-ui';
  18. import {
  19. API,
  20. copy,
  21. showError,
  22. showSuccess,
  23. } from '../../helpers';
  24. import { ITEMS_PER_PAGE } from '../../constants';
  25. import { useTableCompactMode } from '../common/useTableCompactMode';
  26. export const useTokensData = () => {
  27. const { t } = useTranslation();
  28. // Basic state
  29. const [tokens, setTokens] = useState([]);
  30. const [loading, setLoading] = useState(true);
  31. const [activePage, setActivePage] = useState(1);
  32. const [tokenCount, setTokenCount] = useState(0);
  33. const [pageSize, setPageSize] = useState(ITEMS_PER_PAGE);
  34. const [searching, setSearching] = useState(false);
  35. // Selection state
  36. const [selectedKeys, setSelectedKeys] = useState([]);
  37. // Edit state
  38. const [showEdit, setShowEdit] = useState(false);
  39. const [editingToken, setEditingToken] = useState({
  40. id: undefined,
  41. });
  42. // UI state
  43. const [compactMode, setCompactMode] = useTableCompactMode('tokens');
  44. const [showKeys, setShowKeys] = useState({});
  45. // Form state
  46. const [formApi, setFormApi] = useState(null);
  47. const formInitValues = {
  48. searchKeyword: '',
  49. searchToken: '',
  50. };
  51. // Get form values helper function
  52. const getFormValues = () => {
  53. const formValues = formApi ? formApi.getValues() : {};
  54. return {
  55. searchKeyword: formValues.searchKeyword || '',
  56. searchToken: formValues.searchToken || '',
  57. };
  58. };
  59. // Close edit modal
  60. const closeEdit = () => {
  61. setShowEdit(false);
  62. setTimeout(() => {
  63. setEditingToken({
  64. id: undefined,
  65. });
  66. }, 500);
  67. };
  68. // Sync page data from API response
  69. const syncPageData = (payload) => {
  70. setTokens(payload.items || []);
  71. setTokenCount(payload.total || 0);
  72. setActivePage(payload.page || 1);
  73. setPageSize(payload.page_size || pageSize);
  74. };
  75. // Load tokens function
  76. const loadTokens = async (page = 1, size = pageSize) => {
  77. setLoading(true);
  78. const res = await API.get(`/api/token/?p=${page}&size=${size}`);
  79. const { success, message, data } = res.data;
  80. if (success) {
  81. syncPageData(data);
  82. } else {
  83. showError(message);
  84. }
  85. setLoading(false);
  86. };
  87. // Refresh function
  88. const refresh = async (page = activePage) => {
  89. await loadTokens(page);
  90. setSelectedKeys([]);
  91. };
  92. // Copy text function
  93. const copyText = async (text) => {
  94. if (await copy(text)) {
  95. showSuccess(t('已复制到剪贴板!'));
  96. } else {
  97. Modal.error({
  98. title: t('无法复制到剪贴板,请手动复制'),
  99. content: text,
  100. size: 'large',
  101. });
  102. }
  103. };
  104. // Open link function for chat integrations
  105. const onOpenLink = async (type, url, record) => {
  106. let status = localStorage.getItem('status');
  107. let serverAddress = '';
  108. if (status) {
  109. status = JSON.parse(status);
  110. serverAddress = status.server_address;
  111. }
  112. if (serverAddress === '') {
  113. serverAddress = window.location.origin;
  114. }
  115. if (url.includes('{cherryConfig}') === true) {
  116. let cherryConfig = {
  117. id: 'new-api',
  118. baseUrl: serverAddress,
  119. apiKey: 'sk-' + record.key,
  120. }
  121. let encodedConfig = encodeURIComponent(
  122. btoa(JSON.stringify(cherryConfig))
  123. );
  124. url = url.replaceAll('{cherryConfig}', encodedConfig);
  125. } else {
  126. let encodedServerAddress = encodeURIComponent(serverAddress);
  127. url = url.replaceAll('{address}', encodedServerAddress);
  128. url = url.replaceAll('{key}', 'sk-' + record.key);
  129. }
  130. window.open(url, '_blank');
  131. };
  132. // Manage token function (delete, enable, disable)
  133. const manageToken = async (id, action, record) => {
  134. setLoading(true);
  135. let data = { id };
  136. let res;
  137. switch (action) {
  138. case 'delete':
  139. res = await API.delete(`/api/token/${id}/`);
  140. break;
  141. case 'enable':
  142. data.status = 1;
  143. res = await API.put('/api/token/?status_only=true', data);
  144. break;
  145. case 'disable':
  146. data.status = 2;
  147. res = await API.put('/api/token/?status_only=true', data);
  148. break;
  149. }
  150. const { success, message } = res.data;
  151. if (success) {
  152. showSuccess('操作成功完成!');
  153. let token = res.data.data;
  154. let newTokens = [...tokens];
  155. if (action !== 'delete') {
  156. record.status = token.status;
  157. }
  158. setTokens(newTokens);
  159. } else {
  160. showError(message);
  161. }
  162. setLoading(false);
  163. };
  164. // Search tokens function
  165. const searchTokens = async () => {
  166. const { searchKeyword, searchToken } = getFormValues();
  167. if (searchKeyword === '' && searchToken === '') {
  168. await loadTokens(1);
  169. return;
  170. }
  171. setSearching(true);
  172. const res = await API.get(
  173. `/api/token/search?keyword=${searchKeyword}&token=${searchToken}`,
  174. );
  175. const { success, message, data } = res.data;
  176. if (success) {
  177. setTokens(data);
  178. setTokenCount(data.length);
  179. setActivePage(1);
  180. } else {
  181. showError(message);
  182. }
  183. setSearching(false);
  184. };
  185. // Sort tokens function
  186. const sortToken = (key) => {
  187. if (tokens.length === 0) return;
  188. setLoading(true);
  189. let sortedTokens = [...tokens];
  190. sortedTokens.sort((a, b) => {
  191. return ('' + a[key]).localeCompare(b[key]);
  192. });
  193. if (sortedTokens[0].id === tokens[0].id) {
  194. sortedTokens.reverse();
  195. }
  196. setTokens(sortedTokens);
  197. setLoading(false);
  198. };
  199. // Page handlers
  200. const handlePageChange = (page) => {
  201. loadTokens(page, pageSize).then();
  202. };
  203. const handlePageSizeChange = async (size) => {
  204. setPageSize(size);
  205. await loadTokens(1, size);
  206. };
  207. // Row selection handlers
  208. const rowSelection = {
  209. onSelect: (record, selected) => { },
  210. onSelectAll: (selected, selectedRows) => { },
  211. onChange: (selectedRowKeys, selectedRows) => {
  212. setSelectedKeys(selectedRows);
  213. },
  214. };
  215. // Handle row styling
  216. const handleRow = (record, index) => {
  217. if (record.status !== 1) {
  218. return {
  219. style: {
  220. background: 'var(--semi-color-disabled-border)',
  221. },
  222. };
  223. } else {
  224. return {};
  225. }
  226. };
  227. // Batch delete tokens
  228. const batchDeleteTokens = async () => {
  229. if (selectedKeys.length === 0) {
  230. showError(t('请先选择要删除的令牌!'));
  231. return;
  232. }
  233. setLoading(true);
  234. try {
  235. const ids = selectedKeys.map((token) => token.id);
  236. const res = await API.post('/api/token/batch', { ids });
  237. if (res?.data?.success) {
  238. const count = res.data.data || 0;
  239. showSuccess(t('已删除 {{count}} 个令牌!', { count }));
  240. await refresh();
  241. setTimeout(() => {
  242. if (tokens.length === 0 && activePage > 1) {
  243. refresh(activePage - 1);
  244. }
  245. }, 100);
  246. } else {
  247. showError(res?.data?.message || t('删除失败'));
  248. }
  249. } catch (error) {
  250. showError(error.message);
  251. } finally {
  252. setLoading(false);
  253. }
  254. };
  255. // Batch copy tokens
  256. const batchCopyTokens = (copyType) => {
  257. if (selectedKeys.length === 0) {
  258. showError(t('请至少选择一个令牌!'));
  259. return;
  260. }
  261. Modal.info({
  262. title: t('复制令牌'),
  263. icon: null,
  264. content: t('请选择你的复制方式'),
  265. footer: (
  266. <div className="flex gap-2">
  267. <button
  268. className="px-3 py-1 bg-gray-200 rounded"
  269. onClick={async () => {
  270. let content = '';
  271. for (let i = 0; i < selectedKeys.length; i++) {
  272. content +=
  273. selectedKeys[i].name + ' sk-' + selectedKeys[i].key + '\n';
  274. }
  275. await copyText(content);
  276. Modal.destroyAll();
  277. }}
  278. >
  279. {t('名称+密钥')}
  280. </button>
  281. <button
  282. className="px-3 py-1 bg-blue-500 text-white rounded"
  283. onClick={async () => {
  284. let content = '';
  285. for (let i = 0; i < selectedKeys.length; i++) {
  286. content += 'sk-' + selectedKeys[i].key + '\n';
  287. }
  288. await copyText(content);
  289. Modal.destroyAll();
  290. }}
  291. >
  292. {t('仅密钥')}
  293. </button>
  294. </div>
  295. ),
  296. });
  297. };
  298. // Initialize data
  299. useEffect(() => {
  300. loadTokens(1)
  301. .then()
  302. .catch((reason) => {
  303. showError(reason);
  304. });
  305. }, [pageSize]);
  306. return {
  307. // Basic state
  308. tokens,
  309. loading,
  310. activePage,
  311. tokenCount,
  312. pageSize,
  313. searching,
  314. // Selection state
  315. selectedKeys,
  316. setSelectedKeys,
  317. // Edit state
  318. showEdit,
  319. setShowEdit,
  320. editingToken,
  321. setEditingToken,
  322. closeEdit,
  323. // UI state
  324. compactMode,
  325. setCompactMode,
  326. showKeys,
  327. setShowKeys,
  328. // Form state
  329. formApi,
  330. setFormApi,
  331. formInitValues,
  332. getFormValues,
  333. // Functions
  334. loadTokens,
  335. refresh,
  336. copyText,
  337. onOpenLink,
  338. manageToken,
  339. searchTokens,
  340. sortToken,
  341. handlePageChange,
  342. handlePageSizeChange,
  343. rowSelection,
  344. handleRow,
  345. batchDeleteTokens,
  346. batchCopyTokens,
  347. syncPageData,
  348. // Translation
  349. t,
  350. };
  351. };