1.优化AI请求替换OpenAI SDK调用,使用httpx和自定义头请求,避免触发部分公益站的cloudflare
2.修复deepseek模型调用问题,舍弃思考过程AI响应内容,只获取结果内容 3.新增会话过期机制,更新后添加到.env中 4.支持用户在生成章节内容时设置字数
This commit is contained in:
@@ -3,6 +3,7 @@ import type { ReactNode } from 'react';
|
||||
import { Navigate, useLocation } from 'react-router-dom';
|
||||
import { Spin } from 'antd';
|
||||
import { authApi } from '../services/api';
|
||||
import { sessionManager } from '../utils/sessionManager';
|
||||
|
||||
interface ProtectedRouteProps {
|
||||
children: ReactNode;
|
||||
@@ -17,11 +18,19 @@ export default function ProtectedRoute({ children }: ProtectedRouteProps) {
|
||||
try {
|
||||
await authApi.getCurrentUser();
|
||||
setIsAuthenticated(true);
|
||||
// 启动会话管理器
|
||||
sessionManager.start();
|
||||
} catch {
|
||||
setIsAuthenticated(false);
|
||||
// 停止会话管理器
|
||||
sessionManager.stop();
|
||||
}
|
||||
};
|
||||
checkAuth();
|
||||
|
||||
return () => {
|
||||
// 组件卸载时不停止会话管理器,让它在整个应用生命周期内运行
|
||||
};
|
||||
}, []);
|
||||
|
||||
if (isAuthenticated === null) {
|
||||
|
||||
@@ -292,7 +292,7 @@ export default function UserMenu() {
|
||||
padding: 0,
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
height: 'calc(100vh - 200px)',
|
||||
height: 'calc(100vh - 380px)',
|
||||
}
|
||||
}}
|
||||
>
|
||||
@@ -314,7 +314,7 @@ export default function UserMenu() {
|
||||
rowKey="user_id"
|
||||
loading={loading}
|
||||
pagination={false}
|
||||
scroll={{ x: 800, y: 'calc(100vh - 340px)' }}
|
||||
scroll={{ x: 800, y: 'calc(100vh - 520px)' }}
|
||||
sticky
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import { List, Button, Modal, Form, Input, Select, message, Empty, Space, Badge, Tag, Card, Tooltip } from 'antd';
|
||||
import { List, Button, Modal, Form, Input, Select, message, Empty, Space, Badge, Tag, Card, Tooltip, InputNumber } from 'antd';
|
||||
import { EditOutlined, FileTextOutlined, ThunderboltOutlined, LockOutlined, DownloadOutlined, SettingOutlined } from '@ant-design/icons';
|
||||
import { useStore } from '../store';
|
||||
import { useChapterSync } from '../store/hooks';
|
||||
@@ -22,6 +22,7 @@ export default function Chapters() {
|
||||
const contentTextAreaRef = useRef<any>(null);
|
||||
const [writingStyles, setWritingStyles] = useState<WritingStyle[]>([]);
|
||||
const [selectedStyleId, setSelectedStyleId] = useState<number | undefined>();
|
||||
const [targetWordCount, setTargetWordCount] = useState<number>(3000);
|
||||
|
||||
useEffect(() => {
|
||||
const handleResize = () => {
|
||||
@@ -167,7 +168,7 @@ export default function Chapters() {
|
||||
textArea.scrollTop = textArea.scrollHeight;
|
||||
}
|
||||
}
|
||||
}, selectedStyleId);
|
||||
}, selectedStyleId, targetWordCount);
|
||||
|
||||
message.success('AI创作成功');
|
||||
} catch (error) {
|
||||
@@ -201,6 +202,7 @@ export default function Chapters() {
|
||||
{selectedStyle && (
|
||||
<li><strong>写作风格:{selectedStyle.name}</strong></li>
|
||||
)}
|
||||
<li><strong>目标字数:{targetWordCount}字</strong></li>
|
||||
</ul>
|
||||
|
||||
{previousChapters.length > 0 && (
|
||||
@@ -519,7 +521,7 @@ export default function Chapters() {
|
||||
} : undefined}
|
||||
styles={{
|
||||
body: {
|
||||
maxHeight: isMobile ? 'calc(100vh - 150px)' : 'calc(85vh - 110px)',
|
||||
maxHeight: isMobile ? 'calc(100vh - 150px)' : 'calc(100vh - 110px)',
|
||||
overflowY: 'auto',
|
||||
padding: isMobile ? '16px 12px' : '8px'
|
||||
}
|
||||
@@ -592,6 +594,27 @@ export default function Chapters() {
|
||||
)}
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item
|
||||
label="目标字数"
|
||||
tooltip="AI生成章节时的目标字数,实际生成字数可能略有偏差"
|
||||
>
|
||||
<InputNumber
|
||||
min={500}
|
||||
max={10000}
|
||||
step={100}
|
||||
value={targetWordCount}
|
||||
onChange={(value) => setTargetWordCount(value || 3000)}
|
||||
size="large"
|
||||
disabled={isGenerating}
|
||||
style={{ width: '100%' }}
|
||||
formatter={(value) => `${value} 字`}
|
||||
parser={(value) => value?.replace(' 字', '') as any}
|
||||
/>
|
||||
<div style={{ color: '#666', fontSize: 12, marginTop: 4 }}>
|
||||
建议范围:500-10000字,默认3000字
|
||||
</div>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item label="章节内容" name="content">
|
||||
<TextArea
|
||||
ref={contentTextAreaRef}
|
||||
|
||||
@@ -25,6 +25,7 @@ export default function ProjectWizardNew() {
|
||||
const [form] = Form.useForm();
|
||||
const [characterForm] = Form.useForm();
|
||||
const [worldForm] = Form.useForm();
|
||||
const [generateForm] = Form.useForm();
|
||||
const [current, setCurrent] = useState(0);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [isResumingWizard, setIsResumingWizard] = useState(false);
|
||||
@@ -814,11 +815,85 @@ export default function ProjectWizardNew() {
|
||||
return (
|
||||
<Card>
|
||||
<div style={{ marginBottom: 16 }}>
|
||||
<Title level={isMobile ? 5 : 4} style={{ margin: 0, fontSize: isMobile ? 16 : undefined }}>
|
||||
角色与组织列表 (当前: {safeCharacters.length}个,目标: {requiredCharacterCount}个)
|
||||
</Title>
|
||||
<div style={{
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: isMobile ? 'flex-start' : 'center',
|
||||
marginBottom: 12,
|
||||
flexDirection: isMobile ? 'column' : 'row',
|
||||
gap: isMobile ? 12 : 0
|
||||
}}>
|
||||
<Title level={isMobile ? 5 : 4} style={{ margin: 0, fontSize: isMobile ? 16 : undefined }}>
|
||||
角色与组织列表 (当前: {safeCharacters.length}个,目标: {requiredCharacterCount}个)
|
||||
</Title>
|
||||
<Button
|
||||
type="dashed"
|
||||
icon={<TeamOutlined />}
|
||||
onClick={() => {
|
||||
Modal.confirm({
|
||||
title: 'AI生成角色',
|
||||
width: 600,
|
||||
centered: true,
|
||||
content: (
|
||||
<Form form={generateForm} layout="vertical" style={{ marginTop: 16 }}>
|
||||
<Form.Item
|
||||
label="角色名称"
|
||||
name="name"
|
||||
>
|
||||
<Input placeholder="如:张三、李四(可选,AI会自动生成)" />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
label="角色定位"
|
||||
name="role_type"
|
||||
rules={[{ required: true, message: '请选择角色定位' }]}
|
||||
>
|
||||
<Select placeholder="选择角色定位">
|
||||
<Select.Option value="protagonist">主角</Select.Option>
|
||||
<Select.Option value="supporting">配角</Select.Option>
|
||||
<Select.Option value="antagonist">反派</Select.Option>
|
||||
</Select>
|
||||
</Form.Item>
|
||||
<Form.Item label="背景设定" name="background">
|
||||
<TextArea rows={3} placeholder="简要描述角色背景和故事环境..." />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
),
|
||||
okText: '生成',
|
||||
cancelText: '取消',
|
||||
onOk: async () => {
|
||||
try {
|
||||
const values = await generateForm.validateFields();
|
||||
setLoading(true);
|
||||
|
||||
// 调用单个角色生成API
|
||||
const newCharacter = await characterApi.generateCharacter({
|
||||
project_id: projectId,
|
||||
name: values.name,
|
||||
role_type: values.role_type,
|
||||
background: values.background,
|
||||
});
|
||||
|
||||
// 添加到列表
|
||||
setCharacters([...safeCharacters, newCharacter]);
|
||||
message.success('AI生成角色成功');
|
||||
generateForm.resetFields();
|
||||
} catch (error) {
|
||||
const apiError = error as ApiError;
|
||||
message.error('AI生成失败:' + (apiError.response?.data?.detail || apiError.message || '未知错误'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
});
|
||||
}}
|
||||
disabled={loading}
|
||||
size={isMobile ? 'middle' : 'middle'}
|
||||
>
|
||||
AI生成角色
|
||||
</Button>
|
||||
</div>
|
||||
<Paragraph type="secondary" style={{ margin: '8px 0 0 0', fontSize: isMobile ? 12 : 14 }}>
|
||||
所有角色均由AI生成,您可以点击卡片上的编辑按钮进行调整
|
||||
所有角色均由AI生成,您可以点击卡片上的编辑按钮进行调整,或使用"AI生成角色"按钮继续生成
|
||||
</Paragraph>
|
||||
</div>
|
||||
|
||||
|
||||
+203
-25
@@ -1,7 +1,7 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { Card, Form, Input, Button, Select, Slider, InputNumber, message, Space, Typography, Spin, Modal, Tooltip, Alert, Grid } from 'antd';
|
||||
import { SettingOutlined, SaveOutlined, DeleteOutlined, ReloadOutlined, ArrowLeftOutlined, InfoCircleOutlined} from '@ant-design/icons';
|
||||
import { SettingOutlined, SaveOutlined, DeleteOutlined, ReloadOutlined, ArrowLeftOutlined, InfoCircleOutlined, CheckCircleOutlined, CloseCircleOutlined, ThunderboltOutlined } from '@ant-design/icons';
|
||||
import { settingsApi } from '../services/api';
|
||||
import type { SettingsUpdate } from '../types';
|
||||
|
||||
@@ -21,6 +21,17 @@ export default function SettingsPage() {
|
||||
const [modelOptions, setModelOptions] = useState<Array<{ value: string; label: string; description: string }>>([]);
|
||||
const [fetchingModels, setFetchingModels] = useState(false);
|
||||
const [modelsFetched, setModelsFetched] = useState(false);
|
||||
const [testingApi, setTestingApi] = useState(false);
|
||||
const [testResult, setTestResult] = useState<{
|
||||
success: boolean;
|
||||
message: string;
|
||||
response_time_ms?: number;
|
||||
response_preview?: string;
|
||||
error?: string;
|
||||
error_type?: string;
|
||||
suggestions?: string[];
|
||||
} | null>(null);
|
||||
const [showTestResult, setShowTestResult] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
loadSettings();
|
||||
@@ -178,6 +189,52 @@ export default function SettingsPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const handleTestConnection = async () => {
|
||||
const apiKey = form.getFieldValue('api_key');
|
||||
const apiBaseUrl = form.getFieldValue('api_base_url');
|
||||
const provider = form.getFieldValue('api_provider');
|
||||
const modelName = form.getFieldValue('model_name');
|
||||
|
||||
if (!apiKey || !apiBaseUrl || !provider || !modelName) {
|
||||
message.warning('请先填写完整的配置信息');
|
||||
return;
|
||||
}
|
||||
|
||||
setTestingApi(true);
|
||||
setTestResult(null);
|
||||
|
||||
try {
|
||||
const result = await settingsApi.testApiConnection({
|
||||
api_key: apiKey,
|
||||
api_base_url: apiBaseUrl,
|
||||
provider: provider,
|
||||
model_name: modelName
|
||||
});
|
||||
|
||||
setTestResult(result);
|
||||
setShowTestResult(true);
|
||||
|
||||
if (result.success) {
|
||||
message.success(`测试成功!响应时间: ${result.response_time_ms}ms`);
|
||||
} else {
|
||||
message.error('API 测试失败,请查看详细信息');
|
||||
}
|
||||
} catch (error: any) {
|
||||
const errorMsg = error?.response?.data?.detail || '测试请求失败';
|
||||
message.error(errorMsg);
|
||||
setTestResult({
|
||||
success: false,
|
||||
message: '测试请求失败',
|
||||
error: errorMsg,
|
||||
error_type: 'RequestError',
|
||||
suggestions: ['请检查网络连接', '请确认后端服务是否正常运行']
|
||||
});
|
||||
setShowTestResult(true);
|
||||
} finally {
|
||||
setTestingApi(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div style={{
|
||||
minHeight: '100vh',
|
||||
@@ -491,6 +548,94 @@ export default function SettingsPage() {
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
{/* 测试结果展示 */}
|
||||
{showTestResult && testResult && (
|
||||
<Alert
|
||||
message={
|
||||
<Space>
|
||||
{testResult.success ? (
|
||||
<CheckCircleOutlined style={{ color: '#52c41a', fontSize: isMobile ? '16px' : '18px' }} />
|
||||
) : (
|
||||
<CloseCircleOutlined style={{ color: '#ff4d4f', fontSize: isMobile ? '16px' : '18px' }} />
|
||||
)}
|
||||
<span style={{ fontSize: isMobile ? '14px' : '16px', fontWeight: 500 }}>
|
||||
{testResult.message}
|
||||
</span>
|
||||
</Space>
|
||||
}
|
||||
description={
|
||||
<div style={{ marginTop: 8 }}>
|
||||
{testResult.success ? (
|
||||
<Space direction="vertical" size="small" style={{ width: '100%' }}>
|
||||
{testResult.response_time_ms && (
|
||||
<div style={{ fontSize: isMobile ? '12px' : '14px' }}>
|
||||
⚡ 响应时间: <strong>{testResult.response_time_ms} ms</strong>
|
||||
</div>
|
||||
)}
|
||||
{testResult.response_preview && (
|
||||
<div style={{
|
||||
fontSize: isMobile ? '12px' : '13px',
|
||||
padding: '8px 12px',
|
||||
background: '#f6ffed',
|
||||
borderRadius: '4px',
|
||||
border: '1px solid #b7eb8f',
|
||||
marginTop: '8px'
|
||||
}}>
|
||||
<div style={{ marginBottom: '4px', fontWeight: 500 }}>AI 响应预览:</div>
|
||||
<div style={{ color: '#595959' }}>{testResult.response_preview}</div>
|
||||
</div>
|
||||
)}
|
||||
<div style={{ color: '#52c41a', fontSize: isMobile ? '12px' : '13px', marginTop: '4px' }}>
|
||||
✓ API 配置正确,可以正常使用
|
||||
</div>
|
||||
</Space>
|
||||
) : (
|
||||
<Space direction="vertical" size="small" style={{ width: '100%' }}>
|
||||
{testResult.error && (
|
||||
<div style={{
|
||||
fontSize: isMobile ? '12px' : '13px',
|
||||
padding: '8px 12px',
|
||||
background: '#fff2e8',
|
||||
borderRadius: '4px',
|
||||
border: '1px solid #ffbb96',
|
||||
color: '#d4380d'
|
||||
}}>
|
||||
<strong>错误信息:</strong> {testResult.error}
|
||||
</div>
|
||||
)}
|
||||
{testResult.error_type && (
|
||||
<div style={{ fontSize: isMobile ? '11px' : '12px', color: '#8c8c8c' }}>
|
||||
错误类型: {testResult.error_type}
|
||||
</div>
|
||||
)}
|
||||
{testResult.suggestions && testResult.suggestions.length > 0 && (
|
||||
<div style={{ marginTop: '8px' }}>
|
||||
<div style={{ fontSize: isMobile ? '12px' : '13px', fontWeight: 500, marginBottom: '4px' }}>
|
||||
💡 解决建议:
|
||||
</div>
|
||||
<ul style={{
|
||||
margin: 0,
|
||||
paddingLeft: isMobile ? '16px' : '20px',
|
||||
fontSize: isMobile ? '12px' : '13px',
|
||||
color: '#595959'
|
||||
}}>
|
||||
{testResult.suggestions.map((suggestion, index) => (
|
||||
<li key={index} style={{ marginBottom: '4px' }}>{suggestion}</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
</Space>
|
||||
)}
|
||||
</div>
|
||||
}
|
||||
type={testResult.success ? 'success' : 'error'}
|
||||
closable
|
||||
onClose={() => setShowTestResult(false)}
|
||||
style={{ marginBottom: isMobile ? 16 : 24 }}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* 操作按钮 */}
|
||||
<Form.Item style={{ marginBottom: 0, marginTop: isMobile ? 24 : 32 }}>
|
||||
{isMobile ? (
|
||||
@@ -535,9 +680,58 @@ export default function SettingsPage() {
|
||||
</Space>
|
||||
</Space>
|
||||
) : (
|
||||
// 桌面端:原有的水平布局
|
||||
<Space size="middle" style={{ width: '100%', justifyContent: 'space-between' }}>
|
||||
<Space>
|
||||
// 桌面端:删除在左边,测试、重置和保存在右边
|
||||
<div style={{
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
gap: '16px',
|
||||
flexWrap: 'wrap'
|
||||
}}>
|
||||
{/* 左侧:删除按钮 */}
|
||||
{hasSettings ? (
|
||||
<Button
|
||||
danger
|
||||
size="large"
|
||||
icon={<DeleteOutlined />}
|
||||
onClick={handleDelete}
|
||||
loading={loading}
|
||||
style={{
|
||||
minWidth: '100px'
|
||||
}}
|
||||
>
|
||||
删除配置
|
||||
</Button>
|
||||
) : (
|
||||
<div /> // 占位符,保持右侧按钮位置
|
||||
)}
|
||||
|
||||
{/* 右侧:测试、重置和保存按钮组 */}
|
||||
<Space size="middle">
|
||||
<Button
|
||||
size="large"
|
||||
icon={<ThunderboltOutlined />}
|
||||
onClick={handleTestConnection}
|
||||
loading={testingApi}
|
||||
style={{
|
||||
borderColor: '#52c41a',
|
||||
color: '#52c41a',
|
||||
fontWeight: 500,
|
||||
minWidth: '100px'
|
||||
}}
|
||||
>
|
||||
{testingApi ? '测试中...' : '测试'}
|
||||
</Button>
|
||||
<Button
|
||||
size="large"
|
||||
icon={<ReloadOutlined />}
|
||||
onClick={handleReset}
|
||||
style={{
|
||||
minWidth: '100px'
|
||||
}}
|
||||
>
|
||||
重置
|
||||
</Button>
|
||||
<Button
|
||||
type="primary"
|
||||
size="large"
|
||||
@@ -546,31 +740,15 @@ export default function SettingsPage() {
|
||||
loading={loading}
|
||||
style={{
|
||||
background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
|
||||
border: 'none'
|
||||
border: 'none',
|
||||
minWidth: '120px',
|
||||
fontWeight: 500
|
||||
}}
|
||||
>
|
||||
保存设置
|
||||
</Button>
|
||||
<Button
|
||||
size="large"
|
||||
icon={<ReloadOutlined />}
|
||||
onClick={handleReset}
|
||||
>
|
||||
重置
|
||||
保存
|
||||
</Button>
|
||||
</Space>
|
||||
{hasSettings && (
|
||||
<Button
|
||||
danger
|
||||
size="large"
|
||||
icon={<DeleteOutlined />}
|
||||
onClick={handleDelete}
|
||||
loading={loading}
|
||||
>
|
||||
删除设置
|
||||
</Button>
|
||||
)}
|
||||
</Space>
|
||||
</div>
|
||||
)}
|
||||
</Form.Item>
|
||||
</Form>
|
||||
|
||||
@@ -328,9 +328,9 @@ export default function WritingStyles() {
|
||||
createForm.resetFields();
|
||||
}}
|
||||
footer={null}
|
||||
centered={!isMobile}
|
||||
width={isMobile ? '100%' : 600}
|
||||
style={isMobile ? { top: 0, paddingBottom: 0, maxWidth: '100vw' } : undefined}
|
||||
centered
|
||||
width={isMobile ? 'calc(100vw - 32px)' : 600}
|
||||
style={isMobile ? { maxWidth: 'calc(100vw - 32px)', margin: '0 16px' } : undefined}
|
||||
>
|
||||
<Form
|
||||
form={createForm}
|
||||
@@ -387,9 +387,9 @@ export default function WritingStyles() {
|
||||
setEditingStyle(null);
|
||||
}}
|
||||
footer={null}
|
||||
centered={!isMobile}
|
||||
width={isMobile ? '100%' : 600}
|
||||
style={isMobile ? { top: 0, paddingBottom: 0, maxWidth: '100vw' } : undefined}
|
||||
centered
|
||||
width={isMobile ? 'calc(100vw - 32px)' : 600}
|
||||
style={isMobile ? { maxWidth: 'calc(100vw - 32px)', margin: '0 16px' } : undefined}
|
||||
>
|
||||
<Form form={editForm} layout="vertical" onFinish={handleUpdate} style={{ marginTop: 16 }}>
|
||||
<Form.Item
|
||||
|
||||
@@ -115,6 +115,8 @@ export const authApi = {
|
||||
|
||||
getCurrentUser: () => api.get<unknown, User>('/auth/user'),
|
||||
|
||||
refreshSession: () => api.post<unknown, { message: string; expire_at: number; remaining_minutes: number }>('/auth/refresh'),
|
||||
|
||||
logout: () => api.post('/auth/logout'),
|
||||
};
|
||||
|
||||
@@ -144,6 +146,20 @@ export const settingsApi = {
|
||||
|
||||
getAvailableModels: (params: { api_key: string; api_base_url: string; provider: string }) =>
|
||||
api.get<unknown, { provider: string; models: Array<{ value: string; label: string; description: string }>; count?: number }>('/settings/models', { params }),
|
||||
|
||||
testApiConnection: (params: { api_key: string; api_base_url: string; provider: string; model_name: string }) =>
|
||||
api.post<unknown, {
|
||||
success: boolean;
|
||||
message: string;
|
||||
response_time_ms?: number;
|
||||
provider?: string;
|
||||
model?: string;
|
||||
response_preview?: string;
|
||||
details?: Record<string, boolean>;
|
||||
error?: string;
|
||||
error_type?: string;
|
||||
suggestions?: string[];
|
||||
}>('/settings/test', params),
|
||||
};
|
||||
|
||||
export const projectApi = {
|
||||
|
||||
@@ -302,7 +302,8 @@ export function useChapterSync() {
|
||||
const generateChapterContentStream = useCallback(async (
|
||||
chapterId: string,
|
||||
onProgress?: (content: string) => void,
|
||||
styleId?: number
|
||||
styleId?: number,
|
||||
targetWordCount?: number
|
||||
) => {
|
||||
try {
|
||||
// 使用fetch处理流式响应
|
||||
@@ -311,7 +312,10 @@ export function useChapterSync() {
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(styleId ? { style_id: styleId } : {}),
|
||||
body: JSON.stringify({
|
||||
style_id: styleId,
|
||||
target_word_count: targetWordCount
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
|
||||
@@ -224,6 +224,12 @@ export interface ChapterUpdate {
|
||||
status?: 'draft' | 'writing' | 'completed';
|
||||
}
|
||||
|
||||
// 章节生成请求类型
|
||||
export interface ChapterGenerateRequest {
|
||||
style_id?: number;
|
||||
target_word_count?: number;
|
||||
}
|
||||
|
||||
// 章节生成检查响应
|
||||
export interface ChapterCanGenerateResponse {
|
||||
can_generate: boolean;
|
||||
|
||||
@@ -0,0 +1,241 @@
|
||||
import { authApi } from '../services/api';
|
||||
import { message } from 'antd';
|
||||
|
||||
/**
|
||||
* 会话管理工具
|
||||
* 负责监控会话状态、自动刷新和过期处理
|
||||
*/
|
||||
class SessionManager {
|
||||
private checkInterval: number | null = null;
|
||||
private activityTimeout: number | null = null;
|
||||
private lastActivityTime: number = Date.now();
|
||||
|
||||
// 配置参数
|
||||
private readonly CHECK_INTERVAL = 60 * 1000; // 每分钟检查一次
|
||||
private readonly REFRESH_THRESHOLD = 30 * 60 * 1000; // 剩余30分钟时刷新
|
||||
private readonly ACTIVITY_TIMEOUT = 30 * 60 * 1000; // 30分钟无活动则不自动刷新
|
||||
private readonly WARNING_THRESHOLD = 5 * 60 * 1000; // 剩余5分钟时警告
|
||||
|
||||
private warningShown = false;
|
||||
|
||||
/**
|
||||
* 启动会话监控
|
||||
*/
|
||||
start() {
|
||||
// 先检查是否有有效的会话
|
||||
const expireAt = this.getSessionExpireTime();
|
||||
|
||||
if (!expireAt) {
|
||||
return;
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
const remaining = expireAt - now;
|
||||
const remainingMinutes = Math.floor(remaining / 60000);
|
||||
|
||||
// 如果会话已过期,不启动监控
|
||||
if (remaining <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`✅ [会话] 启动监控,剩余 ${remainingMinutes} 分钟`);
|
||||
|
||||
// 立即检查一次
|
||||
this.checkSession();
|
||||
|
||||
// 定期检查会话状态
|
||||
this.checkInterval = setInterval(() => {
|
||||
this.checkSession();
|
||||
}, this.CHECK_INTERVAL);
|
||||
|
||||
// 监听用户活动
|
||||
this.setupActivityListeners();
|
||||
}
|
||||
|
||||
/**
|
||||
* 停止会话监控
|
||||
*/
|
||||
stop() {
|
||||
console.log('[SessionManager] 停止会话监控');
|
||||
|
||||
if (this.checkInterval) {
|
||||
clearInterval(this.checkInterval);
|
||||
this.checkInterval = null;
|
||||
}
|
||||
|
||||
if (this.activityTimeout) {
|
||||
clearTimeout(this.activityTimeout);
|
||||
this.activityTimeout = null;
|
||||
}
|
||||
|
||||
this.removeActivityListeners();
|
||||
this.warningShown = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查会话状态
|
||||
*/
|
||||
private async checkSession() {
|
||||
try {
|
||||
const expireAt = this.getSessionExpireTime();
|
||||
|
||||
if (!expireAt) {
|
||||
this.stop();
|
||||
return;
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
const remaining = expireAt - now;
|
||||
const remainingMinutes = Math.floor(remaining / 60000);
|
||||
|
||||
// 会话已过期
|
||||
if (remaining <= 0) {
|
||||
console.log('⏰ [会话] 已过期,退出登录');
|
||||
this.handleSessionExpired();
|
||||
return;
|
||||
}
|
||||
|
||||
// 显示即将过期警告
|
||||
if (remaining <= this.WARNING_THRESHOLD && !this.warningShown) {
|
||||
this.warningShown = true;
|
||||
message.warning({
|
||||
content: `您的登录状态将在 ${remainingMinutes} 分钟后过期,请注意保存数据`,
|
||||
duration: 10,
|
||||
});
|
||||
}
|
||||
|
||||
// 需要刷新会话
|
||||
if (remaining <= this.REFRESH_THRESHOLD) {
|
||||
const timeSinceLastActivity = now - this.lastActivityTime;
|
||||
|
||||
// 检查用户是否活跃(30分钟内有活动)
|
||||
if (timeSinceLastActivity < this.ACTIVITY_TIMEOUT) {
|
||||
await this.refreshSession();
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
// 静默处理错误
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 刷新会话
|
||||
*/
|
||||
private async refreshSession() {
|
||||
try {
|
||||
const result = await authApi.refreshSession();
|
||||
this.warningShown = false; // 重置警告状态
|
||||
|
||||
console.log(`🔄 [会话] 自动续期成功,延长 ${result.remaining_minutes} 分钟`);
|
||||
|
||||
message.success({
|
||||
content: '登录状态已自动延长',
|
||||
duration: 2,
|
||||
});
|
||||
} catch {
|
||||
// 刷新失败可能是会话已过期
|
||||
this.handleSessionExpired();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理会话过期
|
||||
*/
|
||||
private async handleSessionExpired() {
|
||||
this.stop();
|
||||
|
||||
const currentPath = window.location.pathname;
|
||||
// 如果已经在登录页或回调页,不显示错误提示
|
||||
if (currentPath === '/login' || currentPath === '/auth/callback') {
|
||||
return;
|
||||
}
|
||||
|
||||
// 调用登出接口清除服务器端的 Cookie
|
||||
try {
|
||||
await authApi.logout();
|
||||
} catch {
|
||||
// 即使登出失败也继续跳转
|
||||
}
|
||||
|
||||
message.error({
|
||||
content: '登录已过期,请重新登录',
|
||||
duration: 3,
|
||||
});
|
||||
|
||||
// 延迟跳转,让用户看到提示
|
||||
setTimeout(() => {
|
||||
window.location.href = `/login?redirect=${encodeURIComponent(currentPath)}`;
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取会话过期时间(毫秒时间戳)
|
||||
*/
|
||||
private getSessionExpireTime(): number | null {
|
||||
const cookies = document.cookie.split(';');
|
||||
|
||||
for (const cookie of cookies) {
|
||||
const [name, value] = cookie.trim().split('=');
|
||||
|
||||
if (name === 'session_expire_at') {
|
||||
const timestamp = parseInt(value, 10);
|
||||
return timestamp * 1000; // 转换为毫秒
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置用户活动监听器
|
||||
*/
|
||||
private setupActivityListeners() {
|
||||
const events = ['mousedown', 'keydown', 'scroll', 'touchstart'];
|
||||
|
||||
events.forEach(event => {
|
||||
document.addEventListener(event, this.handleUserActivity, { passive: true });
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 移除用户活动监听器
|
||||
*/
|
||||
private removeActivityListeners() {
|
||||
const events = ['mousedown', 'keydown', 'scroll', 'touchstart'];
|
||||
|
||||
events.forEach(event => {
|
||||
document.removeEventListener(event, this.handleUserActivity);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理用户活动
|
||||
*/
|
||||
private handleUserActivity = () => {
|
||||
this.lastActivityTime = Date.now();
|
||||
|
||||
// 重置活动超时
|
||||
if (this.activityTimeout) {
|
||||
clearTimeout(this.activityTimeout);
|
||||
}
|
||||
|
||||
this.activityTimeout = setTimeout(() => {
|
||||
// 用户已超过30分钟无活动
|
||||
}, this.ACTIVITY_TIMEOUT);
|
||||
};
|
||||
|
||||
/**
|
||||
* 手动刷新会话(供外部调用)
|
||||
*/
|
||||
async manualRefresh(): Promise<boolean> {
|
||||
try {
|
||||
await this.refreshSession();
|
||||
return true;
|
||||
} catch (error) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 导出单例
|
||||
export const sessionManager = new SessionManager();
|
||||
Reference in New Issue
Block a user