useTokensData.js 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  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 = (openFluentNotification) => {
  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. if (url && url.startsWith('fluent')) {
  107. openFluentNotification(record.key);
  108. return;
  109. }
  110. let status = localStorage.getItem('status');
  111. let serverAddress = '';
  112. if (status) {
  113. status = JSON.parse(status);
  114. serverAddress = status.server_address;
  115. }
  116. if (serverAddress === '') {
  117. serverAddress = window.location.origin;
  118. }
  119. if (url.includes('{cherryConfig}') === true) {
  120. let cherryConfig = {
  121. id: 'new-api',
  122. baseUrl: serverAddress,
  123. apiKey: 'sk-' + record.key,
  124. }
  125. let encodedConfig = encodeURIComponent(
  126. btoa(JSON.stringify(cherryConfig))
  127. );
  128. url = url.replaceAll('{cherryConfig}', encodedConfig);
  129. } else {
  130. let encodedServerAddress = encodeURIComponent(serverAddress);
  131. url = url.replaceAll('{address}', encodedServerAddress);
  132. url = url.replaceAll('{key}', 'sk-' + record.key);
  133. }
  134. window.open(url, '_blank');
  135. };
  136. // Manage token function (delete, enable, disable)
  137. const manageToken = async (id, action, record) => {
  138. setLoading(true);
  139. let data = { id };
  140. let res;
  141. switch (action) {
  142. case 'delete':
  143. res = await API.delete(`/api/token/${id}/`);
  144. break;
  145. case 'enable':
  146. data.status = 1;
  147. res = await API.put('/api/token/?status_only=true', data);
  148. break;
  149. case 'disable':
  150. data.status = 2;
  151. res = await API.put('/api/token/?status_only=true', data);
  152. break;
  153. }
  154. const { success, message } = res.data;
  155. if (success) {
  156. showSuccess('操作成功完成!');
  157. let token = res.data.data;
  158. let newTokens = [...tokens];
  159. if (action !== 'delete') {
  160. record.status = token.status;
  161. }
  162. setTokens(newTokens);
  163. } else {
  164. showError(message);
  165. }
  166. setLoading(false);
  167. };
  168. // Search tokens function
  169. const searchTokens = async () => {
  170. const { searchKeyword, searchToken } = getFormValues();
  171. if (searchKeyword === '' && searchToken === '') {
  172. await loadTokens(1);
  173. return;
  174. }
  175. setSearching(true);
  176. const res = await API.get(
  177. `/api/token/search?keyword=${searchKeyword}&token=${searchToken}`,
  178. );
  179. const { success, message, data } = res.data;
  180. if (success) {
  181. setTokens(data);
  182. setTokenCount(data.length);
  183. setActivePage(1);
  184. } else {
  185. showError(message);
  186. }
  187. setSearching(false);
  188. };
  189. // Sort tokens function
  190. const sortToken = (key) => {
  191. if (tokens.length === 0) return;
  192. setLoading(true);
  193. let sortedTokens = [...tokens];
  194. sortedTokens.sort((a, b) => {
  195. return ('' + a[key]).localeCompare(b[key]);
  196. });
  197. if (sortedTokens[0].id === tokens[0].id) {
  198. sortedTokens.reverse();
  199. }
  200. setTokens(sortedTokens);
  201. setLoading(false);
  202. };
  203. // Page handlers
  204. const handlePageChange = (page) => {
  205. loadTokens(page, pageSize).then();
  206. };
  207. const handlePageSizeChange = async (size) => {
  208. setPageSize(size);
  209. await loadTokens(1, size);
  210. };
  211. // Row selection handlers
  212. const rowSelection = {
  213. onSelect: (record, selected) => { },
  214. onSelectAll: (selected, selectedRows) => { },
  215. onChange: (selectedRowKeys, selectedRows) => {
  216. setSelectedKeys(selectedRows);
  217. },
  218. };
  219. // Handle row styling
  220. const handleRow = (record, index) => {
  221. if (record.status !== 1) {
  222. return {
  223. style: {
  224. background: 'var(--semi-color-disabled-border)',
  225. },
  226. };
  227. } else {
  228. return {};
  229. }
  230. };
  231. // Batch delete tokens
  232. const batchDeleteTokens = async () => {
  233. if (selectedKeys.length === 0) {
  234. showError(t('请先选择要删除的令牌!'));
  235. return;
  236. }
  237. setLoading(true);
  238. try {
  239. const ids = selectedKeys.map((token) => token.id);
  240. const res = await API.post('/api/token/batch', { ids });
  241. if (res?.data?.success) {
  242. const count = res.data.data || 0;
  243. showSuccess(t('已删除 {{count}} 个令牌!', { count }));
  244. await refresh();
  245. setTimeout(() => {
  246. if (tokens.length === 0 && activePage > 1) {
  247. refresh(activePage - 1);
  248. }
  249. }, 100);
  250. } else {
  251. showError(res?.data?.message || t('删除失败'));
  252. }
  253. } catch (error) {
  254. showError(error.message);
  255. } finally {
  256. setLoading(false);
  257. }
  258. };
  259. // Batch copy tokens
  260. const batchCopyTokens = (copyType) => {
  261. if (selectedKeys.length === 0) {
  262. showError(t('请至少选择一个令牌!'));
  263. return;
  264. }
  265. Modal.info({
  266. title: t('复制令牌'),
  267. icon: null,
  268. content: t('请选择你的复制方式'),
  269. footer: (
  270. <div className="flex gap-2">
  271. <button
  272. className="px-3 py-1 bg-gray-200 rounded"
  273. onClick={async () => {
  274. let content = '';
  275. for (let i = 0; i < selectedKeys.length; i++) {
  276. content +=
  277. selectedKeys[i].name + ' sk-' + selectedKeys[i].key + '\n';
  278. }
  279. await copyText(content);
  280. Modal.destroyAll();
  281. }}
  282. >
  283. {t('名称+密钥')}
  284. </button>
  285. <button
  286. className="px-3 py-1 bg-blue-500 text-white rounded"
  287. onClick={async () => {
  288. let content = '';
  289. for (let i = 0; i < selectedKeys.length; i++) {
  290. content += 'sk-' + selectedKeys[i].key + '\n';
  291. }
  292. await copyText(content);
  293. Modal.destroyAll();
  294. }}
  295. >
  296. {t('仅密钥')}
  297. </button>
  298. </div>
  299. ),
  300. });
  301. };
  302. // Initialize data
  303. useEffect(() => {
  304. loadTokens(1)
  305. .then()
  306. .catch((reason) => {
  307. showError(reason);
  308. });
  309. }, [pageSize]);
  310. return {
  311. // Basic state
  312. tokens,
  313. loading,
  314. activePage,
  315. tokenCount,
  316. pageSize,
  317. searching,
  318. // Selection state
  319. selectedKeys,
  320. setSelectedKeys,
  321. // Edit state
  322. showEdit,
  323. setShowEdit,
  324. editingToken,
  325. setEditingToken,
  326. closeEdit,
  327. // UI state
  328. compactMode,
  329. setCompactMode,
  330. showKeys,
  331. setShowKeys,
  332. // Form state
  333. formApi,
  334. setFormApi,
  335. formInitValues,
  336. getFormValues,
  337. // Functions
  338. loadTokens,
  339. refresh,
  340. copyText,
  341. onOpenLink,
  342. manageToken,
  343. searchTokens,
  344. sortToken,
  345. handlePageChange,
  346. handlePageSizeChange,
  347. rowSelection,
  348. handleRow,
  349. batchDeleteTokens,
  350. batchCopyTokens,
  351. syncPageData,
  352. // Translation
  353. t,
  354. };
  355. };