PersonalSetting.js 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193
  1. import React, { useContext, useEffect, useState } from 'react';
  2. import { useNavigate } from 'react-router-dom';
  3. import {
  4. API,
  5. copy,
  6. isRoot,
  7. showError,
  8. showInfo,
  9. showSuccess,
  10. } from '../helpers';
  11. import Turnstile from 'react-turnstile';
  12. import { UserContext } from '../context/User';
  13. import {
  14. onGitHubOAuthClicked,
  15. onOIDCClicked,
  16. onLinuxDOOAuthClicked,
  17. } from './utils';
  18. import {
  19. Avatar,
  20. Banner,
  21. Button,
  22. Card,
  23. Descriptions,
  24. Image,
  25. Input,
  26. InputNumber,
  27. Layout,
  28. Modal,
  29. Space,
  30. Tag,
  31. Typography,
  32. Collapsible,
  33. Select,
  34. Radio,
  35. RadioGroup,
  36. AutoComplete,
  37. Checkbox,
  38. Tabs,
  39. TabPane,
  40. } from '@douyinfe/semi-ui';
  41. import {
  42. getQuotaPerUnit,
  43. renderQuota,
  44. renderQuotaWithPrompt,
  45. stringToColor,
  46. } from '../helpers/render';
  47. import TelegramLoginButton from 'react-telegram-login';
  48. import { useTranslation } from 'react-i18next';
  49. const PersonalSetting = () => {
  50. const [userState, userDispatch] = useContext(UserContext);
  51. let navigate = useNavigate();
  52. const { t } = useTranslation();
  53. const [inputs, setInputs] = useState({
  54. wechat_verification_code: '',
  55. email_verification_code: '',
  56. email: '',
  57. self_account_deletion_confirmation: '',
  58. original_password: '',
  59. set_new_password: '',
  60. set_new_password_confirmation: '',
  61. });
  62. const [status, setStatus] = useState({});
  63. const [showChangePasswordModal, setShowChangePasswordModal] = useState(false);
  64. const [showWeChatBindModal, setShowWeChatBindModal] = useState(false);
  65. const [showEmailBindModal, setShowEmailBindModal] = useState(false);
  66. const [showAccountDeleteModal, setShowAccountDeleteModal] = useState(false);
  67. const [turnstileEnabled, setTurnstileEnabled] = useState(false);
  68. const [turnstileSiteKey, setTurnstileSiteKey] = useState('');
  69. const [turnstileToken, setTurnstileToken] = useState('');
  70. const [loading, setLoading] = useState(false);
  71. const [disableButton, setDisableButton] = useState(false);
  72. const [countdown, setCountdown] = useState(30);
  73. const [affLink, setAffLink] = useState('');
  74. const [systemToken, setSystemToken] = useState('');
  75. const [models, setModels] = useState([]);
  76. const [openTransfer, setOpenTransfer] = useState(false);
  77. const [transferAmount, setTransferAmount] = useState(0);
  78. const [isModelsExpanded, setIsModelsExpanded] = useState(() => {
  79. // Initialize from localStorage if available
  80. const savedState = localStorage.getItem('modelsExpanded');
  81. return savedState ? JSON.parse(savedState) : false;
  82. });
  83. const MODELS_DISPLAY_COUNT = 10; // 默认显示的模型数量
  84. const [notificationSettings, setNotificationSettings] = useState({
  85. warningType: 'email',
  86. warningThreshold: 100000,
  87. webhookUrl: '',
  88. webhookSecret: '',
  89. notificationEmail: '',
  90. acceptUnsetModelRatioModel: false,
  91. });
  92. const [showWebhookDocs, setShowWebhookDocs] = useState(false);
  93. useEffect(() => {
  94. let status = localStorage.getItem('status');
  95. if (status) {
  96. status = JSON.parse(status);
  97. setStatus(status);
  98. if (status.turnstile_check) {
  99. setTurnstileEnabled(true);
  100. setTurnstileSiteKey(status.turnstile_site_key);
  101. }
  102. }
  103. getUserData().then((res) => {
  104. console.log(userState);
  105. });
  106. loadModels().then();
  107. getAffLink().then();
  108. setTransferAmount(getQuotaPerUnit());
  109. }, []);
  110. useEffect(() => {
  111. let countdownInterval = null;
  112. if (disableButton && countdown > 0) {
  113. countdownInterval = setInterval(() => {
  114. setCountdown(countdown - 1);
  115. }, 1000);
  116. } else if (countdown === 0) {
  117. setDisableButton(false);
  118. setCountdown(30);
  119. }
  120. return () => clearInterval(countdownInterval); // Clean up on unmount
  121. }, [disableButton, countdown]);
  122. useEffect(() => {
  123. if (userState?.user?.setting) {
  124. const settings = JSON.parse(userState.user.setting);
  125. setNotificationSettings({
  126. warningType: settings.notify_type || 'email',
  127. warningThreshold: settings.quota_warning_threshold || 500000,
  128. webhookUrl: settings.webhook_url || '',
  129. webhookSecret: settings.webhook_secret || '',
  130. notificationEmail: settings.notification_email || '',
  131. acceptUnsetModelRatioModel:
  132. settings.accept_unset_model_ratio_model || false,
  133. });
  134. }
  135. }, [userState?.user?.setting]);
  136. // Save models expanded state to localStorage whenever it changes
  137. useEffect(() => {
  138. localStorage.setItem('modelsExpanded', JSON.stringify(isModelsExpanded));
  139. }, [isModelsExpanded]);
  140. const handleInputChange = (name, value) => {
  141. setInputs((inputs) => ({ ...inputs, [name]: value }));
  142. };
  143. const generateAccessToken = async () => {
  144. const res = await API.get('/api/user/token');
  145. const { success, message, data } = res.data;
  146. if (success) {
  147. setSystemToken(data);
  148. await copy(data);
  149. showSuccess(t('令牌已重置并已复制到剪贴板'));
  150. } else {
  151. showError(message);
  152. }
  153. };
  154. const getAffLink = async () => {
  155. const res = await API.get('/api/user/aff');
  156. const { success, message, data } = res.data;
  157. if (success) {
  158. let link = `${window.location.origin}/register?aff=${data}`;
  159. setAffLink(link);
  160. } else {
  161. showError(message);
  162. }
  163. };
  164. const getUserData = async () => {
  165. let res = await API.get(`/api/user/self`);
  166. const { success, message, data } = res.data;
  167. if (success) {
  168. userDispatch({ type: 'login', payload: data });
  169. } else {
  170. showError(message);
  171. }
  172. };
  173. const loadModels = async () => {
  174. let res = await API.get(`/api/user/models`);
  175. const { success, message, data } = res.data;
  176. if (success) {
  177. if (data != null) {
  178. setModels(data);
  179. }
  180. } else {
  181. showError(message);
  182. }
  183. };
  184. const handleAffLinkClick = async (e) => {
  185. e.target.select();
  186. await copy(e.target.value);
  187. showSuccess(t('邀请链接已复制到剪切板'));
  188. };
  189. const handleSystemTokenClick = async (e) => {
  190. e.target.select();
  191. await copy(e.target.value);
  192. showSuccess(t('系统令牌已复制到剪切板'));
  193. };
  194. const deleteAccount = async () => {
  195. if (inputs.self_account_deletion_confirmation !== userState.user.username) {
  196. showError(t('请输入你的账户名以确认删除!'));
  197. return;
  198. }
  199. const res = await API.delete('/api/user/self');
  200. const { success, message } = res.data;
  201. if (success) {
  202. showSuccess(t('账户已删除!'));
  203. await API.get('/api/user/logout');
  204. userDispatch({ type: 'logout' });
  205. localStorage.removeItem('user');
  206. navigate('/login');
  207. } else {
  208. showError(message);
  209. }
  210. };
  211. const bindWeChat = async () => {
  212. if (inputs.wechat_verification_code === '') return;
  213. const res = await API.get(
  214. `/api/oauth/wechat/bind?code=${inputs.wechat_verification_code}`,
  215. );
  216. const { success, message } = res.data;
  217. if (success) {
  218. showSuccess(t('微信账户绑定成功!'));
  219. setShowWeChatBindModal(false);
  220. } else {
  221. showError(message);
  222. }
  223. };
  224. const changePassword = async () => {
  225. if (inputs.original_password === '') {
  226. showError(t('请输入原密码!'));
  227. return;
  228. }
  229. if (inputs.set_new_password === '') {
  230. showError(t('请输入新密码!'));
  231. return;
  232. }
  233. if (inputs.original_password === inputs.set_new_password) {
  234. showError(t('新密码需要和原密码不一致!'));
  235. return;
  236. }
  237. if (inputs.set_new_password !== inputs.set_new_password_confirmation) {
  238. showError(t('两次输入的密码不一致!'));
  239. return;
  240. }
  241. const res = await API.put(`/api/user/self`, {
  242. original_password: inputs.original_password,
  243. password: inputs.set_new_password,
  244. });
  245. const { success, message } = res.data;
  246. if (success) {
  247. showSuccess(t('密码修改成功!'));
  248. setShowWeChatBindModal(false);
  249. } else {
  250. showError(message);
  251. }
  252. setShowChangePasswordModal(false);
  253. };
  254. const transfer = async () => {
  255. if (transferAmount < getQuotaPerUnit()) {
  256. showError(t('划转金额最低为') + ' ' + renderQuota(getQuotaPerUnit()));
  257. return;
  258. }
  259. const res = await API.post(`/api/user/aff_transfer`, {
  260. quota: transferAmount,
  261. });
  262. const { success, message } = res.data;
  263. if (success) {
  264. showSuccess(message);
  265. setOpenTransfer(false);
  266. getUserData().then();
  267. } else {
  268. showError(message);
  269. }
  270. };
  271. const sendVerificationCode = async () => {
  272. if (inputs.email === '') {
  273. showError(t('请输入邮箱!'));
  274. return;
  275. }
  276. setDisableButton(true);
  277. if (turnstileEnabled && turnstileToken === '') {
  278. showInfo('请稍后几秒重试,Turnstile 正在检查用户环境!');
  279. return;
  280. }
  281. setLoading(true);
  282. const res = await API.get(
  283. `/api/verification?email=${inputs.email}&turnstile=${turnstileToken}`,
  284. );
  285. const { success, message } = res.data;
  286. if (success) {
  287. showSuccess(t('验证码发送成功,请检查邮箱!'));
  288. } else {
  289. showError(message);
  290. }
  291. setLoading(false);
  292. };
  293. const bindEmail = async () => {
  294. if (inputs.email_verification_code === '') {
  295. showError(t('请输入邮箱验证码!'));
  296. return;
  297. }
  298. setLoading(true);
  299. const res = await API.get(
  300. `/api/oauth/email/bind?email=${inputs.email}&code=${inputs.email_verification_code}`,
  301. );
  302. const { success, message } = res.data;
  303. if (success) {
  304. showSuccess(t('邮箱账户绑定成功!'));
  305. setShowEmailBindModal(false);
  306. userState.user.email = inputs.email;
  307. } else {
  308. showError(message);
  309. }
  310. setLoading(false);
  311. };
  312. const getUsername = () => {
  313. if (userState.user) {
  314. return userState.user.username;
  315. } else {
  316. return 'null';
  317. }
  318. };
  319. const handleCancel = () => {
  320. setOpenTransfer(false);
  321. };
  322. const copyText = async (text) => {
  323. if (await copy(text)) {
  324. showSuccess(t('已复制:') + text);
  325. } else {
  326. // setSearchKeyword(text);
  327. Modal.error({ title: t('无法复制到剪贴板,请手动复制'), content: text });
  328. }
  329. };
  330. const handleNotificationSettingChange = (type, value) => {
  331. setNotificationSettings((prev) => ({
  332. ...prev,
  333. [type]: value.target ? value.target.value : value, // 处理 Radio 事件对象
  334. }));
  335. };
  336. const saveNotificationSettings = async () => {
  337. try {
  338. const res = await API.put('/api/user/setting', {
  339. notify_type: notificationSettings.warningType,
  340. quota_warning_threshold: parseFloat(
  341. notificationSettings.warningThreshold,
  342. ),
  343. webhook_url: notificationSettings.webhookUrl,
  344. webhook_secret: notificationSettings.webhookSecret,
  345. notification_email: notificationSettings.notificationEmail,
  346. accept_unset_model_ratio_model:
  347. notificationSettings.acceptUnsetModelRatioModel,
  348. });
  349. if (res.data.success) {
  350. showSuccess(t('通知设置已更新'));
  351. await getUserData();
  352. } else {
  353. showError(res.data.message);
  354. }
  355. } catch (error) {
  356. showError(t('更新通知设置失败'));
  357. }
  358. };
  359. return (
  360. <div>
  361. <Layout>
  362. <Layout.Content>
  363. <Modal
  364. title={t('请输入要划转的数量')}
  365. visible={openTransfer}
  366. onOk={transfer}
  367. onCancel={handleCancel}
  368. maskClosable={false}
  369. size={'small'}
  370. centered={true}
  371. >
  372. <div style={{ marginTop: 20 }}>
  373. <Typography.Text>
  374. {t('可用额度')}
  375. {renderQuotaWithPrompt(userState?.user?.aff_quota)}
  376. </Typography.Text>
  377. <Input
  378. style={{ marginTop: 5 }}
  379. value={userState?.user?.aff_quota}
  380. disabled={true}
  381. ></Input>
  382. </div>
  383. <div style={{ marginTop: 20 }}>
  384. <Typography.Text>
  385. {t('划转额度')}
  386. {renderQuotaWithPrompt(transferAmount)}{' '}
  387. {t('最低') + renderQuota(getQuotaPerUnit())}
  388. </Typography.Text>
  389. <div>
  390. <InputNumber
  391. min={0}
  392. style={{ marginTop: 5 }}
  393. value={transferAmount}
  394. onChange={(value) => setTransferAmount(value)}
  395. disabled={false}
  396. ></InputNumber>
  397. </div>
  398. </div>
  399. </Modal>
  400. <div>
  401. <Card
  402. title={
  403. <Card.Meta
  404. avatar={
  405. <Avatar
  406. size='default'
  407. color={stringToColor(getUsername())}
  408. style={{ marginRight: 4 }}
  409. >
  410. {typeof getUsername() === 'string' &&
  411. getUsername().slice(0, 1)}
  412. </Avatar>
  413. }
  414. title={<Typography.Text>{getUsername()}</Typography.Text>}
  415. description={
  416. isRoot() ? (
  417. <Tag color='red'>{t('管理员')}</Tag>
  418. ) : (
  419. <Tag color='blue'>{t('普通用户')}</Tag>
  420. )
  421. }
  422. ></Card.Meta>
  423. }
  424. headerExtraContent={
  425. <>
  426. <Space vertical align='start'>
  427. <Tag color='green'>{'ID: ' + userState?.user?.id}</Tag>
  428. <Tag color='blue'>{userState?.user?.group}</Tag>
  429. </Space>
  430. </>
  431. }
  432. footer={
  433. <>
  434. <div
  435. style={{ display: 'flex', alignItems: 'center', gap: 8 }}
  436. >
  437. <Typography.Title heading={6}>
  438. {t('可用模型')}
  439. </Typography.Title>
  440. </div>
  441. <div style={{ marginTop: 10 }}>
  442. {models.length <= MODELS_DISPLAY_COUNT ? (
  443. <Space wrap>
  444. {models.map((model) => (
  445. <Tag
  446. key={model}
  447. color='cyan'
  448. onClick={() => {
  449. copyText(model);
  450. }}
  451. >
  452. {model}
  453. </Tag>
  454. ))}
  455. </Space>
  456. ) : (
  457. <>
  458. <Collapsible isOpen={isModelsExpanded}>
  459. <Space wrap>
  460. {models.map((model) => (
  461. <Tag
  462. key={model}
  463. color='cyan'
  464. onClick={() => {
  465. copyText(model);
  466. }}
  467. >
  468. {model}
  469. </Tag>
  470. ))}
  471. <Tag
  472. color='blue'
  473. type='light'
  474. style={{ cursor: 'pointer' }}
  475. onClick={() => setIsModelsExpanded(false)}
  476. >
  477. {t('收起')}
  478. </Tag>
  479. </Space>
  480. </Collapsible>
  481. {!isModelsExpanded && (
  482. <Space wrap>
  483. {models
  484. .slice(0, MODELS_DISPLAY_COUNT)
  485. .map((model) => (
  486. <Tag
  487. key={model}
  488. color='cyan'
  489. onClick={() => {
  490. copyText(model);
  491. }}
  492. >
  493. {model}
  494. </Tag>
  495. ))}
  496. <Tag
  497. color='blue'
  498. type='light'
  499. style={{ cursor: 'pointer' }}
  500. onClick={() => setIsModelsExpanded(true)}
  501. >
  502. {t('更多')} {models.length - MODELS_DISPLAY_COUNT}{' '}
  503. {t('个模型')}
  504. </Tag>
  505. </Space>
  506. )}
  507. </>
  508. )}
  509. </div>
  510. </>
  511. }
  512. >
  513. <Descriptions row>
  514. <Descriptions.Item itemKey={t('当前余额')}>
  515. {renderQuota(userState?.user?.quota)}
  516. </Descriptions.Item>
  517. <Descriptions.Item itemKey={t('历史消耗')}>
  518. {renderQuota(userState?.user?.used_quota)}
  519. </Descriptions.Item>
  520. <Descriptions.Item itemKey={t('请求次数')}>
  521. {userState.user?.request_count}
  522. </Descriptions.Item>
  523. </Descriptions>
  524. </Card>
  525. <Card
  526. style={{ marginTop: 10 }}
  527. footer={
  528. <div>
  529. <Typography.Text>{t('邀请链接')}</Typography.Text>
  530. <Input
  531. style={{ marginTop: 10 }}
  532. value={affLink}
  533. onClick={handleAffLinkClick}
  534. readOnly
  535. />
  536. </div>
  537. }
  538. >
  539. <Typography.Title heading={6}>{t('邀请信息')}</Typography.Title>
  540. <div style={{ marginTop: 10 }}>
  541. <Descriptions row>
  542. <Descriptions.Item itemKey={t('待使用收益')}>
  543. <span style={{ color: 'rgba(var(--semi-red-5), 1)' }}>
  544. {renderQuota(userState?.user?.aff_quota)}
  545. </span>
  546. <Button
  547. type={'secondary'}
  548. onClick={() => setOpenTransfer(true)}
  549. size={'small'}
  550. style={{ marginLeft: 10 }}
  551. >
  552. {t('划转')}
  553. </Button>
  554. </Descriptions.Item>
  555. <Descriptions.Item itemKey={t('总收益')}>
  556. {renderQuota(userState?.user?.aff_history_quota)}
  557. </Descriptions.Item>
  558. <Descriptions.Item itemKey={t('邀请人数')}>
  559. {userState?.user?.aff_count}
  560. </Descriptions.Item>
  561. </Descriptions>
  562. </div>
  563. </Card>
  564. <Card style={{ marginTop: 10 }}>
  565. <Typography.Title heading={6}>{t('个人信息')}</Typography.Title>
  566. <div style={{ marginTop: 20 }}>
  567. <Typography.Text strong>{t('邮箱')}</Typography.Text>
  568. <div
  569. style={{ display: 'flex', justifyContent: 'space-between' }}
  570. >
  571. <div>
  572. <Input
  573. value={
  574. userState.user && userState.user.email !== ''
  575. ? userState.user.email
  576. : t('未绑定')
  577. }
  578. readonly={true}
  579. ></Input>
  580. </div>
  581. <div>
  582. <Button
  583. onClick={() => {
  584. setShowEmailBindModal(true);
  585. }}
  586. >
  587. {userState.user && userState.user.email !== ''
  588. ? t('修改绑定')
  589. : t('绑定邮箱')}
  590. </Button>
  591. </div>
  592. </div>
  593. </div>
  594. <div style={{ marginTop: 10 }}>
  595. <Typography.Text strong>{t('微信')}</Typography.Text>
  596. <div
  597. style={{ display: 'flex', justifyContent: 'space-between' }}
  598. >
  599. <div>
  600. <Input
  601. value={
  602. userState.user && userState.user.wechat_id !== ''
  603. ? t('已绑定')
  604. : t('未绑定')
  605. }
  606. readonly={true}
  607. ></Input>
  608. </div>
  609. <div>
  610. <Button
  611. disabled={!status.wechat_login}
  612. onClick={() => {
  613. setShowWeChatBindModal(true);
  614. }}
  615. >
  616. {userState.user && userState.user.wechat_id !== ''
  617. ? t('修改绑定')
  618. : status.wechat_login
  619. ? t('绑定')
  620. : t('未启用')}
  621. </Button>
  622. </div>
  623. </div>
  624. </div>
  625. <div style={{ marginTop: 10 }}>
  626. <Typography.Text strong>{t('GitHub')}</Typography.Text>
  627. <div
  628. style={{ display: 'flex', justifyContent: 'space-between' }}
  629. >
  630. <div>
  631. <Input
  632. value={
  633. userState.user && userState.user.github_id !== ''
  634. ? userState.user.github_id
  635. : t('未绑定')
  636. }
  637. readonly={true}
  638. ></Input>
  639. </div>
  640. <div>
  641. <Button
  642. onClick={() => {
  643. onGitHubOAuthClicked(status.github_client_id);
  644. }}
  645. disabled={
  646. (userState.user && userState.user.github_id !== '') ||
  647. !status.github_oauth
  648. }
  649. >
  650. {status.github_oauth ? t('绑定') : t('未启用')}
  651. </Button>
  652. </div>
  653. </div>
  654. </div>
  655. <div style={{ marginTop: 10 }}>
  656. <Typography.Text strong>{t('OIDC')}</Typography.Text>
  657. <div
  658. style={{ display: 'flex', justifyContent: 'space-between' }}
  659. >
  660. <div>
  661. <Input
  662. value={
  663. userState.user && userState.user.oidc_id !== ''
  664. ? userState.user.oidc_id
  665. : t('未绑定')
  666. }
  667. readonly={true}
  668. ></Input>
  669. </div>
  670. <div>
  671. <Button
  672. onClick={() => {
  673. onOIDCClicked(
  674. status.oidc_authorization_endpoint,
  675. status.oidc_client_id,
  676. );
  677. }}
  678. disabled={
  679. (userState.user && userState.user.oidc_id !== '') ||
  680. !status.oidc_enabled
  681. }
  682. >
  683. {status.oidc_enabled ? t('绑定') : t('未启用')}
  684. </Button>
  685. </div>
  686. </div>
  687. </div>
  688. <div style={{ marginTop: 10 }}>
  689. <Typography.Text strong>{t('Telegram')}</Typography.Text>
  690. <div
  691. style={{ display: 'flex', justifyContent: 'space-between' }}
  692. >
  693. <div>
  694. <Input
  695. value={
  696. userState.user && userState.user.telegram_id !== ''
  697. ? userState.user.telegram_id
  698. : t('未绑定')
  699. }
  700. readonly={true}
  701. ></Input>
  702. </div>
  703. <div>
  704. {status.telegram_oauth ? (
  705. userState.user.telegram_id !== '' ? (
  706. <Button disabled={true}>{t('已绑定')}</Button>
  707. ) : (
  708. <TelegramLoginButton
  709. dataAuthUrl='/api/oauth/telegram/bind'
  710. botName={status.telegram_bot_name}
  711. />
  712. )
  713. ) : (
  714. <Button disabled={true}>{t('未启用')}</Button>
  715. )}
  716. </div>
  717. </div>
  718. </div>
  719. <div style={{ marginTop: 10 }}>
  720. <Typography.Text strong>{t('LinuxDO')}</Typography.Text>
  721. <div
  722. style={{ display: 'flex', justifyContent: 'space-between' }}
  723. >
  724. <div>
  725. <Input
  726. value={
  727. userState.user && userState.user.linux_do_id !== ''
  728. ? userState.user.linux_do_id
  729. : t('未绑定')
  730. }
  731. readonly={true}
  732. ></Input>
  733. </div>
  734. <div>
  735. <Button
  736. onClick={() => {
  737. onLinuxDOOAuthClicked(status.linuxdo_client_id);
  738. }}
  739. disabled={
  740. (userState.user && userState.user.linux_do_id !== '') ||
  741. !status.linuxdo_oauth
  742. }
  743. >
  744. {status.linuxdo_oauth ? t('绑定') : t('未启用')}
  745. </Button>
  746. </div>
  747. </div>
  748. </div>
  749. <div style={{ marginTop: 10 }}>
  750. <Space>
  751. <Button onClick={generateAccessToken}>
  752. {t('生成系统访问令牌')}
  753. </Button>
  754. <Button
  755. onClick={() => {
  756. setShowChangePasswordModal(true);
  757. }}
  758. >
  759. {t('修改密码')}
  760. </Button>
  761. <Button
  762. type={'danger'}
  763. onClick={() => {
  764. setShowAccountDeleteModal(true);
  765. }}
  766. >
  767. {t('删除个人账户')}
  768. </Button>
  769. </Space>
  770. {systemToken && (
  771. <Input
  772. readOnly
  773. value={systemToken}
  774. onClick={handleSystemTokenClick}
  775. style={{ marginTop: '10px' }}
  776. />
  777. )}
  778. <Modal
  779. onCancel={() => setShowWeChatBindModal(false)}
  780. visible={showWeChatBindModal}
  781. size={'small'}
  782. >
  783. <Image src={status.wechat_qrcode} />
  784. <div style={{ textAlign: 'center' }}>
  785. <p>
  786. 微信扫码关注公众号,输入「验证码」获取验证码(三分钟内有效)
  787. </p>
  788. </div>
  789. <Input
  790. placeholder='验证码'
  791. name='wechat_verification_code'
  792. value={inputs.wechat_verification_code}
  793. onChange={(v) =>
  794. handleInputChange('wechat_verification_code', v)
  795. }
  796. />
  797. <Button color='' fluid size='large' onClick={bindWeChat}>
  798. {t('绑定')}
  799. </Button>
  800. </Modal>
  801. </div>
  802. </Card>
  803. <Card style={{ marginTop: 10 }}>
  804. <Tabs type='line' defaultActiveKey='notification'>
  805. <TabPane tab={t('通知设置')} itemKey='notification'>
  806. <div style={{ marginTop: 20 }}>
  807. <Typography.Text strong>{t('通知方式')}</Typography.Text>
  808. <div style={{ marginTop: 10 }}>
  809. <RadioGroup
  810. value={notificationSettings.warningType}
  811. onChange={(value) =>
  812. handleNotificationSettingChange('warningType', value)
  813. }
  814. >
  815. <Radio value='email'>{t('邮件通知')}</Radio>
  816. <Radio value='webhook'>{t('Webhook通知')}</Radio>
  817. </RadioGroup>
  818. </div>
  819. </div>
  820. {notificationSettings.warningType === 'webhook' && (
  821. <>
  822. <div style={{ marginTop: 20 }}>
  823. <Typography.Text strong>
  824. {t('Webhook地址')}
  825. </Typography.Text>
  826. <div style={{ marginTop: 10 }}>
  827. <Input
  828. value={notificationSettings.webhookUrl}
  829. onChange={(val) =>
  830. handleNotificationSettingChange('webhookUrl', val)
  831. }
  832. placeholder={t(
  833. '请输入Webhook地址,例如: https://example.com/webhook',
  834. )}
  835. />
  836. <Typography.Text
  837. type='secondary'
  838. style={{ marginTop: 8, display: 'block' }}
  839. >
  840. {t(
  841. '只支持https,系统将以 POST 方式发送通知,请确保地址可以接收 POST 请求',
  842. )}
  843. </Typography.Text>
  844. <Typography.Text
  845. type='secondary'
  846. style={{ marginTop: 8, display: 'block' }}
  847. >
  848. <div
  849. style={{ cursor: 'pointer' }}
  850. onClick={() =>
  851. setShowWebhookDocs(!showWebhookDocs)
  852. }
  853. >
  854. {t('Webhook请求结构')}{' '}
  855. {showWebhookDocs ? '▼' : '▶'}
  856. </div>
  857. <Collapsible isOpen={showWebhookDocs}>
  858. <pre
  859. style={{
  860. marginTop: 4,
  861. background: 'var(--semi-color-fill-0)',
  862. padding: 8,
  863. borderRadius: 4,
  864. }}
  865. >
  866. {`{
  867. "type": "quota_exceed", // 通知类型
  868. "title": "标题", // 通知标题
  869. "content": "通知内容", // 通知内容,支持 {{value}} 变量占位符
  870. "values": ["值1", "值2"], // 按顺序替换content中的 {{value}} 占位符
  871. "timestamp": 1739950503 // 时间戳
  872. }
  873. 示例:
  874. {
  875. "type": "quota_exceed",
  876. "title": "额度预警通知",
  877. "content": "您的额度即将用尽,当前剩余额度为 {{value}}",
  878. "values": ["$0.99"],
  879. "timestamp": 1739950503
  880. }`}
  881. </pre>
  882. </Collapsible>
  883. </Typography.Text>
  884. </div>
  885. </div>
  886. <div style={{ marginTop: 20 }}>
  887. <Typography.Text strong>
  888. {t('接口凭证(可选)')}
  889. </Typography.Text>
  890. <div style={{ marginTop: 10 }}>
  891. <Input
  892. value={notificationSettings.webhookSecret}
  893. onChange={(val) =>
  894. handleNotificationSettingChange(
  895. 'webhookSecret',
  896. val,
  897. )
  898. }
  899. placeholder={t('请输入密钥')}
  900. />
  901. <Typography.Text
  902. type='secondary'
  903. style={{ marginTop: 8, display: 'block' }}
  904. >
  905. {t(
  906. '密钥将以 Bearer 方式添加到请求头中,用于验证webhook请求的合法性',
  907. )}
  908. </Typography.Text>
  909. <Typography.Text
  910. type='secondary'
  911. style={{ marginTop: 4, display: 'block' }}
  912. >
  913. {t('Authorization: Bearer your-secret-key')}
  914. </Typography.Text>
  915. </div>
  916. </div>
  917. </>
  918. )}
  919. {notificationSettings.warningType === 'email' && (
  920. <div style={{ marginTop: 20 }}>
  921. <Typography.Text strong>{t('通知邮箱')}</Typography.Text>
  922. <div style={{ marginTop: 10 }}>
  923. <Input
  924. value={notificationSettings.notificationEmail}
  925. onChange={(val) =>
  926. handleNotificationSettingChange(
  927. 'notificationEmail',
  928. val,
  929. )
  930. }
  931. placeholder={t('留空则使用账号绑定的邮箱')}
  932. />
  933. <Typography.Text
  934. type='secondary'
  935. style={{ marginTop: 8, display: 'block' }}
  936. >
  937. {t(
  938. '设置用于接收额度预警的邮箱地址,不填则使用账号绑定的邮箱',
  939. )}
  940. </Typography.Text>
  941. </div>
  942. </div>
  943. )}
  944. <div style={{ marginTop: 20 }}>
  945. <Typography.Text strong>
  946. {t('额度预警阈值')}{' '}
  947. {renderQuotaWithPrompt(
  948. notificationSettings.warningThreshold,
  949. )}
  950. </Typography.Text>
  951. <div style={{ marginTop: 10 }}>
  952. <AutoComplete
  953. value={notificationSettings.warningThreshold}
  954. onChange={(val) =>
  955. handleNotificationSettingChange(
  956. 'warningThreshold',
  957. val,
  958. )
  959. }
  960. style={{ width: 200 }}
  961. placeholder={t('请输入预警额度')}
  962. data={[
  963. { value: 100000, label: '0.2$' },
  964. { value: 500000, label: '1$' },
  965. { value: 1000000, label: '5$' },
  966. { value: 5000000, label: '10$' },
  967. ]}
  968. />
  969. </div>
  970. <Typography.Text
  971. type='secondary'
  972. style={{ marginTop: 10, display: 'block' }}
  973. >
  974. {t(
  975. '当剩余额度低于此数值时,系统将通过选择的方式发送通知',
  976. )}
  977. </Typography.Text>
  978. </div>
  979. </TabPane>
  980. <TabPane tab={t('价格设置')} itemKey='price'>
  981. <div style={{ marginTop: 20 }}>
  982. <Typography.Text strong>
  983. {t('接受未设置价格模型')}
  984. </Typography.Text>
  985. <div style={{ marginTop: 10 }}>
  986. <Checkbox
  987. checked={
  988. notificationSettings.acceptUnsetModelRatioModel
  989. }
  990. onChange={(e) =>
  991. handleNotificationSettingChange(
  992. 'acceptUnsetModelRatioModel',
  993. e.target.checked,
  994. )
  995. }
  996. >
  997. {t('接受未设置价格模型')}
  998. </Checkbox>
  999. <Typography.Text
  1000. type='secondary'
  1001. style={{ marginTop: 8, display: 'block' }}
  1002. >
  1003. {t(
  1004. '当模型没有设置价格时仍接受调用,仅当您信任该网站时使用,可能会产生高额费用',
  1005. )}
  1006. </Typography.Text>
  1007. </div>
  1008. </div>
  1009. </TabPane>
  1010. </Tabs>
  1011. <div style={{ marginTop: 20 }}>
  1012. <Button type='primary' onClick={saveNotificationSettings}>
  1013. {t('保存设置')}
  1014. </Button>
  1015. </div>
  1016. </Card>
  1017. <Modal
  1018. onCancel={() => setShowEmailBindModal(false)}
  1019. onOk={bindEmail}
  1020. visible={showEmailBindModal}
  1021. size={'small'}
  1022. centered={true}
  1023. maskClosable={false}
  1024. >
  1025. <Typography.Title heading={6}>
  1026. {t('绑定邮箱地址')}
  1027. </Typography.Title>
  1028. <div
  1029. style={{
  1030. marginTop: 20,
  1031. display: 'flex',
  1032. justifyContent: 'space-between',
  1033. }}
  1034. >
  1035. <Input
  1036. fluid
  1037. placeholder='输入邮箱地址'
  1038. onChange={(value) => handleInputChange('email', value)}
  1039. name='email'
  1040. type='email'
  1041. />
  1042. <Button
  1043. onClick={sendVerificationCode}
  1044. disabled={disableButton || loading}
  1045. >
  1046. {disableButton ? `重新发送 (${countdown})` : '获取验证码'}
  1047. </Button>
  1048. </div>
  1049. <div style={{ marginTop: 10 }}>
  1050. <Input
  1051. fluid
  1052. placeholder='验证码'
  1053. name='email_verification_code'
  1054. value={inputs.email_verification_code}
  1055. onChange={(value) =>
  1056. handleInputChange('email_verification_code', value)
  1057. }
  1058. />
  1059. </div>
  1060. {turnstileEnabled ? (
  1061. <Turnstile
  1062. sitekey={turnstileSiteKey}
  1063. onVerify={(token) => {
  1064. setTurnstileToken(token);
  1065. }}
  1066. />
  1067. ) : (
  1068. <></>
  1069. )}
  1070. </Modal>
  1071. <Modal
  1072. onCancel={() => setShowAccountDeleteModal(false)}
  1073. visible={showAccountDeleteModal}
  1074. size={'small'}
  1075. centered={true}
  1076. onOk={deleteAccount}
  1077. >
  1078. <div style={{ marginTop: 20 }}>
  1079. <Banner
  1080. type='danger'
  1081. description='您正在删除自己的帐户,将清空所有数据且不可恢复'
  1082. closeIcon={null}
  1083. />
  1084. </div>
  1085. <div style={{ marginTop: 20 }}>
  1086. <Input
  1087. placeholder={`输入你的账户名 ${userState?.user?.username} 以确认删除`}
  1088. name='self_account_deletion_confirmation'
  1089. value={inputs.self_account_deletion_confirmation}
  1090. onChange={(value) =>
  1091. handleInputChange(
  1092. 'self_account_deletion_confirmation',
  1093. value,
  1094. )
  1095. }
  1096. />
  1097. {turnstileEnabled ? (
  1098. <Turnstile
  1099. sitekey={turnstileSiteKey}
  1100. onVerify={(token) => {
  1101. setTurnstileToken(token);
  1102. }}
  1103. />
  1104. ) : (
  1105. <></>
  1106. )}
  1107. </div>
  1108. </Modal>
  1109. <Modal
  1110. onCancel={() => setShowChangePasswordModal(false)}
  1111. visible={showChangePasswordModal}
  1112. size={'small'}
  1113. centered={true}
  1114. onOk={changePassword}
  1115. >
  1116. <div style={{ marginTop: 20 }}>
  1117. <Input
  1118. name='original_password'
  1119. placeholder={t('原密码')}
  1120. type='password'
  1121. value={inputs.original_password}
  1122. onChange={(value) =>
  1123. handleInputChange('original_password', value)
  1124. }
  1125. />
  1126. <Input
  1127. style={{ marginTop: 20 }}
  1128. name='set_new_password'
  1129. placeholder={t('新密码')}
  1130. value={inputs.set_new_password}
  1131. onChange={(value) =>
  1132. handleInputChange('set_new_password', value)
  1133. }
  1134. />
  1135. <Input
  1136. style={{ marginTop: 20 }}
  1137. name='set_new_password_confirmation'
  1138. placeholder={t('确认新密码')}
  1139. value={inputs.set_new_password_confirmation}
  1140. onChange={(value) =>
  1141. handleInputChange('set_new_password_confirmation', value)
  1142. }
  1143. />
  1144. {turnstileEnabled ? (
  1145. <Turnstile
  1146. sitekey={turnstileSiteKey}
  1147. onVerify={(token) => {
  1148. setTurnstileToken(token);
  1149. }}
  1150. />
  1151. ) : (
  1152. <></>
  1153. )}
  1154. </div>
  1155. </Modal>
  1156. </div>
  1157. </Layout.Content>
  1158. </Layout>
  1159. </div>
  1160. );
  1161. };
  1162. export default PersonalSetting;