Skip to content

Let's use AI to Earn!

feat: draft-box auto-init without planId + S3 upload proxy via nginx

Sakura82b1eaa219b7
diff --git a/config/aitoearn-server.config.js b/config/aitoearn-server.config.js
index 8098dc94..c5cdc079 100644
--- a/config/aitoearn-server.config.js
+++ b/config/aitoearn-server.config.js
@@ -254,6 +254,8 @@ module.exports = {
region: 'us-east-1',
bucketName: 'aitoearn',
endpoint: 'http://rustfs.local:9000',
+ signEndpoint: 'http://localhost:9000',
+ cdnEndpoint: 'http://localhost:8080/oss',
accessKeyId: 'rustfsadmin',
secretAccessKey: 'rustfsadmin',
},
diff --git a/docker-compose.yml b/docker-compose.yml
index 16351294..44249fde 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -47,7 +47,6 @@ services:
RUSTFS_ACCESS_KEY: rustfsadmin
RUSTFS_SECRET_KEY: rustfsadmin
ports:
- - "9000:9000"
- "9001:9001"
volumes:
- rustfs-data:/data
@@ -280,6 +279,7 @@ services:
condition: service_healthy
ports:
- "8080:80"
+ - "9000:9000"
volumes:
- ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro
networks:
diff --git a/nginx/nginx.conf b/nginx/nginx.conf
index 40719b3a..5615db69 100644
--- a/nginx/nginx.conf
+++ b/nginx/nginx.conf
@@ -100,4 +100,32 @@ http {
proxy_pass http://aitoearn-web:3000;
}
}
+
+ # S3 代理:浏览器通过此端口上传文件到 rustfs
+ server {
+ listen 9000;
+ listen [::]:9000;
+ server_name _;
+
+ client_max_body_size 500m;
+
+ add_header Access-Control-Allow-Origin * always;
+ add_header Access-Control-Allow-Methods "GET, HEAD, PUT, POST, DELETE, OPTIONS" always;
+ add_header Access-Control-Allow-Headers * always;
+ add_header Access-Control-Expose-Headers "ETag" always;
+ add_header Access-Control-Max-Age 86400 always;
+
+ if ($request_method = 'OPTIONS') {
+ return 204;
+ }
+
+ location / {
+ proxy_pass http://aitoearn-rustfs:9000;
+ proxy_set_header Host $http_host;
+ proxy_http_version 1.1;
+ proxy_connect_timeout 120s;
+ proxy_send_timeout 120s;
+ proxy_read_timeout 120s;
+ }
+ }
}
diff --git a/project/aitoearn-backend/libs/aws-s3/src/index.ts b/project/aitoearn-backend/libs/aws-s3/src/index.ts
index 1b390ff9..14690f4a 100644
--- a/project/aitoearn-backend/libs/aws-s3/src/index.ts
+++ b/project/aitoearn-backend/libs/aws-s3/src/index.ts
@@ -1,4 +1,5 @@
export * from './s3.config'
+export * from './s3.constants'
export * from './s3.module'
export * from './s3.service'
export * from './s3.util'
diff --git a/project/aitoearn-backend/libs/aws-s3/src/s3.config.ts b/project/aitoearn-backend/libs/aws-s3/src/s3.config.ts
index f0f99fe2..f5fdf4fc 100644
--- a/project/aitoearn-backend/libs/aws-s3/src/s3.config.ts
+++ b/project/aitoearn-backend/libs/aws-s3/src/s3.config.ts
@@ -6,8 +6,9 @@ export const s3ConfigSchema = z.object({
accessKeyId: z.string().optional(),
secretAccessKey: z.string().optional(),
bucketName: z.string(),
- endpoint: z.httpUrl(),
- cdnEndpoint: z.httpUrl().optional(),
+ endpoint: z.url(),
+ cdnEndpoint: z.url().optional(),
+ signEndpoint: z.url().optional().describe('预签名 URL 使用的外部可达 endpoint,不设置则使用 endpoint'),
signExpires: z.number().default(5 * 60).describe('sign expires in seconds'),
})
diff --git a/project/aitoearn-backend/libs/aws-s3/src/s3.constants.ts b/project/aitoearn-backend/libs/aws-s3/src/s3.constants.ts
new file mode 100644
index 00000000..f79c6b8c
--- /dev/null
+++ b/project/aitoearn-backend/libs/aws-s3/src/s3.constants.ts
@@ -0,0 +1 @@
+export const SIGN_S3_CLIENT = Symbol('SIGN_S3_CLIENT')
diff --git a/project/aitoearn-backend/libs/aws-s3/src/s3.module.ts b/project/aitoearn-backend/libs/aws-s3/src/s3.module.ts
index aec0b952..2f54517e 100644
--- a/project/aitoearn-backend/libs/aws-s3/src/s3.module.ts
+++ b/project/aitoearn-backend/libs/aws-s3/src/s3.module.ts
@@ -2,12 +2,18 @@ import type { DynamicModule, Provider } from '@nestjs/common'
import { S3Client } from '@aws-sdk/client-s3'
import { Global, Module } from '@nestjs/common'
import { S3Config } from './s3.config'
+import { SIGN_S3_CLIENT } from './s3.constants'
import { S3Service } from './s3.service'
@Global()
@Module({})
export class S3Module {
static forRoot(config: S3Config): DynamicModule {
+ const buildCredentials = (s3Config: S3Config) =>
+ s3Config.accessKeyId && s3Config.secretAccessKey
+ ? { accessKeyId: s3Config.accessKeyId, secretAccessKey: s3Config.secretAccessKey }
+ : undefined
+
const providers: Provider[] = [
{
provide: S3Config,
@@ -18,12 +24,18 @@ export class S3Module {
useFactory: (s3Config: S3Config) => new S3Client({
region: s3Config.region,
endpoint: s3Config.endpoint,
- credentials: s3Config.accessKeyId && s3Config.secretAccessKey
- ? {
- accessKeyId: s3Config.accessKeyId,
- secretAccessKey: s3Config.secretAccessKey,
- }
- : undefined,
+ forcePathStyle: true,
+ credentials: buildCredentials(s3Config),
+ }),
+ inject: [S3Config],
+ },
+ {
+ provide: SIGN_S3_CLIENT,
+ useFactory: (s3Config: S3Config) => new S3Client({
+ region: s3Config.region,
+ endpoint: s3Config.signEndpoint || s3Config.endpoint,
+ forcePathStyle: true,
+ credentials: buildCredentials(s3Config),
}),
inject: [S3Config],
},
@@ -34,7 +46,7 @@ export class S3Module {
global: true,
module: S3Module,
providers,
- exports: [S3Service],
+ exports: [S3Service, SIGN_S3_CLIENT],
}
}
}
diff --git a/project/aitoearn-backend/libs/aws-s3/src/s3.service.ts b/project/aitoearn-backend/libs/aws-s3/src/s3.service.ts
index 717c5fd5..c5e8e04c 100644
--- a/project/aitoearn-backend/libs/aws-s3/src/s3.service.ts
+++ b/project/aitoearn-backend/libs/aws-s3/src/s3.service.ts
@@ -15,9 +15,10 @@ import {
import { Upload } from '@aws-sdk/lib-storage'
import { createPresignedPost } from '@aws-sdk/s3-presigned-post'
import { getSignedUrl } from '@aws-sdk/s3-request-presigner'
-import { Injectable, Logger } from '@nestjs/common'
+import { Inject, Injectable, Logger } from '@nestjs/common'
import { AppException, ResponseCode } from '@yikart/common'
import { S3Config } from './s3.config'
+import { SIGN_S3_CLIENT } from './s3.constants'
@Injectable()
export class S3Service {
@@ -26,6 +27,7 @@ export class S3Service {
constructor(
private readonly config: S3Config,
private readonly client: S3Client,
+ @Inject(SIGN_S3_CLIENT) private readonly signClient: S3Client,
) {}
async putObject(
@@ -77,7 +79,7 @@ export class S3Service {
// 生成预签名上传 URL
async getUploadSignPost(objectPath: string, contentType?: string) {
- const result = await createPresignedPost(this.client, {
+ const result = await createPresignedPost(this.signClient, {
Bucket: this.config.bucketName,
Key: objectPath,
Expires: this.config.signExpires,
@@ -88,7 +90,7 @@ export class S3Service {
}
async getUploadSignUrl(objectPath: string, contentType?: string, contentLength?: number) {
- return getSignedUrl(this.client, new PutObjectCommand({
+ return getSignedUrl(this.signClient, new PutObjectCommand({
Bucket: this.config.bucketName,
Key: objectPath,
ContentType: contentType,
@@ -202,7 +204,7 @@ export class S3Service {
* 生成预签名 GET URL(用于让外部服务读取 R2 对象,绕过 CDN 限制)
*/
async getReadSignUrl(objectPath: string, expiresIn = 3600) {
- return getSignedUrl(this.client, new GetObjectCommand({
+ return getSignedUrl(this.signClient, new GetObjectCommand({
Bucket: this.config.bucketName,
Key: objectPath,
}), { expiresIn })
diff --git a/project/aitoearn-web/src/app/[lng]/draft-box/DraftBoxCore.tsx b/project/aitoearn-web/src/app/[lng]/draft-box/DraftBoxCore.tsx
index 1f446485..e1240b2e 100644
--- a/project/aitoearn-web/src/app/[lng]/draft-box/DraftBoxCore.tsx
+++ b/project/aitoearn-web/src/app/[lng]/draft-box/DraftBoxCore.tsx
@@ -1,32 +1,30 @@
/**
* 草稿箱核心组件
- * 管理草稿组选择和内容展示
+ * 自动获取/创建默认草稿箱并展示内容
*/
'use client'
import { Loader2 } from 'lucide-react'
-import { useSearchParams } from 'next/navigation'
import { useEffect } from 'react'
+import { useShallow } from 'zustand/react/shallow'
import DraftContentModule from './components/DraftContentModule'
import { useDraftBoxStore } from './draftBoxStore'
export default function DraftBoxCore() {
- const searchParams = useSearchParams()
- const urlPlanId = searchParams.get('planId')
-
- const initDetailPage = useDraftBoxStore(state => state.initDetailPage)
- const planLoading = useDraftBoxStore(state => state.planLoading)
- const currentPlan = useDraftBoxStore(state => state.currentPlan)
+ const { planLoading, currentPlan } = useDraftBoxStore(
+ useShallow(state => ({
+ planLoading: state.planLoading,
+ currentPlan: state.currentPlan,
+ })),
+ )
+ const autoInit = useDraftBoxStore(state => state.autoInit)
- // 根据 URL 参数初始化数据
useEffect(() => {
- if (urlPlanId) {
- initDetailPage(urlPlanId)
- }
- }, [urlPlanId, initDetailPage])
+ autoInit()
+ }, [autoInit])
- if (urlPlanId && planLoading && !currentPlan) {
+ if (planLoading && !currentPlan) {
return (
<div className="flex flex-col h-full">
<div className="flex-1 min-h-0">
diff --git a/project/aitoearn-web/src/app/[lng]/draft-box/components/DraftListSection.tsx b/project/aitoearn-web/src/app/[lng]/draft-box/components/DraftListSection.tsx
index cff0cd27..205fd542 100644
--- a/project/aitoearn-web/src/app/[lng]/draft-box/components/DraftListSection.tsx
+++ b/project/aitoearn-web/src/app/[lng]/draft-box/components/DraftListSection.tsx
@@ -9,7 +9,7 @@
'use client'
import type { DraftMaterial } from '@/app/[lng]/draft-box/types'
-import { Check, ListChecks, Plus } from 'lucide-react'
+import { Check, FileText, ListChecks, Plus } from 'lucide-react'
import { memo, useCallback, useEffect, useRef } from 'react'
import Masonry from 'react-masonry-css'
import { useShallow } from 'zustand/react/shallow'
@@ -273,6 +273,38 @@ export const DraftListSection = memo(() => {
)
}
+ // 空状态:加载完成且无草稿
+ if (!materialsLoading && materials.length === 0) {
+ return (
+ <Card>
+ <CardHeader className="pb-4">
+ <div className="flex items-center justify-between">
+ <CardTitle className="text-base">{t('overview.draftList', { count: 0 })}</CardTitle>
+ <Button variant="ghost" size="sm" onClick={openGenerationDetailDialog} className="cursor-pointer gap-1.5 text-muted-foreground">
+ <ListChecks className="h-3.5 w-3.5" />
+ {t('draftManage.generationDetail')}
+ </Button>
+ </div>
+ </CardHeader>
+ <CardContent>
+ <div className="flex flex-col items-center justify-center py-16 gap-4">
+ <div className="flex h-16 w-16 items-center justify-center rounded-full bg-muted">
+ <FileText className="h-8 w-8 text-muted-foreground" />
+ </div>
+ <div className="text-center">
+ <p className="text-base font-medium text-muted-foreground">{t('material.emptyTitle')}</p>
+ <p className="mt-1 text-sm text-muted-foreground/70">{t('material.emptyDesc')}</p>
+ </div>
+ <Button onClick={openCreateMaterialModal} className="cursor-pointer mt-2 gap-1.5">
+ <Plus className="h-4 w-4" />
+ {t('detail.manualGenerate')}
+ </Button>
+ </div>
+ </CardContent>
+ </Card>
+ )
+ }
+
return (
<Card>
<CardHeader className="pb-4">
diff --git a/project/aitoearn-web/src/app/[lng]/draft-box/draftBoxStore.ts b/project/aitoearn-web/src/app/[lng]/draft-box/draftBoxStore.ts
index c5f1e292..6fb264df 100644
--- a/project/aitoearn-web/src/app/[lng]/draft-box/draftBoxStore.ts
+++ b/project/aitoearn-web/src/app/[lng]/draft-box/draftBoxStore.ts
@@ -13,8 +13,10 @@ import {
} from '@/api/draftGeneration'
import {
apiBatchDeleteMaterials,
+ apiCreateMaterialGroup,
apiDeleteMaterial,
apiFilterDeleteMaterials,
+ apiGetMaterialGroupList,
apiGetMaterialInfo,
apiGetMaterialList,
} from '@/api/material'
@@ -379,6 +381,46 @@ export const useDraftBoxStore = create(
// ==================== 初始化 ====================
+ /** 自动获取或创建默认草稿箱,然后初始化页面 */
+ autoInit: async () => {
+ const { initializedGroupId } = get()
+
+ set({ planLoading: true })
+ try {
+ // 获取第一个草稿箱
+ const res = await apiGetMaterialGroupList(1, 1)
+ const list = res?.data?.list || []
+
+ let groupId: string
+
+ if (list.length > 0) {
+ groupId = list[0]._id
+ }
+ else {
+ // 没有草稿箱,自动创建一个
+ const createRes = await apiCreateMaterialGroup({ name: '默认草稿箱' })
+ if (createRes?.data?._id) {
+ groupId = createRes.data._id
+ }
+ else {
+ set({ planLoading: false, materialsLoading: false })
+ return
+ }
+ }
+
+ // 防止重复初始化
+ if (initializedGroupId === groupId) {
+ set({ planLoading: false })
+ return
+ }
+
+ await methods.initDetailPage(groupId, true)
+ }
+ catch {
+ set({ planLoading: false, materialsLoading: false })
+ }
+ },
+
initDetailPage: async (groupId: string, force: boolean = false) => {
const { initializedGroupId } = get()
if (!force && initializedGroupId === groupId) {
diff --git a/project/aitoearn-web/src/app/api/auto-login/route.ts b/project/aitoearn-web/src/app/auto-login/route.ts
similarity index 92%
rename from project/aitoearn-web/src/app/api/auto-login/route.ts
rename to project/aitoearn-web/src/app/auto-login/route.ts
index 445daea0..4ad867d3 100644
--- a/project/aitoearn-web/src/app/api/auto-login/route.ts
+++ b/project/aitoearn-web/src/app/auto-login/route.ts
@@ -5,6 +5,8 @@
import { readFileSync } from 'fs'
import { NextResponse } from 'next/server'
+export const dynamic = 'force-dynamic'
+
export function GET() {
const tokenPath = process.env.AUTO_LOGIN_TOKEN_PATH
if (!tokenPath) return NextResponse.json({ token: null })
diff --git a/project/aitoearn-web/src/app/layout/Providers.tsx b/project/aitoearn-web/src/app/layout/Providers.tsx
index 2719478a..28c14a8d 100644
--- a/project/aitoearn-web/src/app/layout/Providers.tsx
+++ b/project/aitoearn-web/src/app/layout/Providers.tsx
@@ -26,10 +26,11 @@ export function Providers({ children, lng }: { children: React.ReactNode, lng: s
// 用于追踪是否已经在当前路由弹出过登录框,避免重复弹出
const hasPromptedRef = useRef(false)
- const { _hasHydrated, token } = useUserStore(
+ const { _hasHydrated, token, _appInitialized } = useUserStore(
useShallow(state => ({
_hasHydrated: state._hasHydrated,
token: state.token,
+ _appInitialized: state._appInitialized,
})),
)
@@ -48,8 +49,8 @@ export function Providers({ children, lng }: { children: React.ReactNode, lng: s
// 未登录用户访问非公开页面时,跳转到登录页
useEffect(() => {
- // 等待持久化数据同步完成
- if (!_hasHydrated) {
+ // 等待持久化数据同步完成和 appInit 完成(含自动登录)
+ if (!_hasHydrated || !_appInitialized) {
return
}
@@ -73,7 +74,7 @@ export function Providers({ children, lng }: { children: React.ReactNode, lng: s
// 在当前页面弹出登录框,不跳转
hasPromptedRef.current = true
useLoginDialogStore.getState().openLoginDialog({ fromGuard: true })
- }, [_hasHydrated, token, pathname])
+ }, [_hasHydrated, _appInitialized, token, pathname])
// 拦截 @react-oauth/google 的脚本加载,添加 ?hl= 参数以设置按钮语言
useLayoutEffect(() => {
diff --git a/project/aitoearn-web/src/middleware.ts b/project/aitoearn-web/src/middleware.ts
index ef64122d..76cb101a 100644
--- a/project/aitoearn-web/src/middleware.ts
+++ b/project/aitoearn-web/src/middleware.ts
@@ -8,7 +8,7 @@ acceptLanguage.languages(languages)
export const config = {
// matcher: '/:lng*'
- matcher: ['/((?!api|_next/static|_next/image|assets|favicon.ico|sw.js|site.webmanifest).*)'],
+ matcher: ['/((?!api|auto-login|_next/static|_next/image|assets|favicon.ico|sw.js|site.webmanifest).*)'],
}
export function middleware(req: NextRequest) {
diff --git a/project/aitoearn-web/src/store/user.ts b/project/aitoearn-web/src/store/user.ts
index 55338c48..378bdaa9 100644
--- a/project/aitoearn-web/src/store/user.ts
+++ b/project/aitoearn-web/src/store/user.ts
@@ -41,6 +41,8 @@ export interface IUserStore {
sidebarCollapsed: boolean
// 是否曾经登录过(用于判断是否显示登录页或重定向到注册页)
hasEverLoggedIn: boolean
+ // appInit 是否已完成(用于路由守卫等待自动登录)
+ _appInitialized: boolean
}
const state: IUserStore = {
@@ -50,6 +52,7 @@ const state: IUserStore = {
lang: i18next.language || 'en',
sidebarCollapsed: false,
hasEverLoggedIn: false,
+ _appInitialized: false,
}
function getState(): IUserStore {
@@ -82,11 +85,12 @@ export const useUserStore = createPersistStore(
// 自动登录:从 init 服务生成的 token 文件中获取
if (!_get().token) {
try {
- const res = await fetch('/api/auto-login')
+ const res = await fetch('/auto-login')
const data = await res.json()
if (data.token) methods.setToken(data.token)
} catch {}
}
+ set({ _appInitialized: true })
methods.getUserInfo()
useAccountStore.getState().accountInit()
},
diff --git a/scripts/init.mjs b/scripts/init.mjs
index 834b2e39..48098c02 100644
--- a/scripts/init.mjs
+++ b/scripts/init.mjs
@@ -21,7 +21,7 @@ async function main() {
console.log('Connected to MongoDB')
const db = client.db(DB_NAME)
- const users = db.collection('users')
+ const users = db.collection('user')
let user = await users.findOne({ mail: DEFAULT_EMAIL, isDelete: { $ne: true } })