diff --git a/package.json b/package.json index 201a1e8a..54fed347 100644 --- a/package.json +++ b/package.json @@ -3,11 +3,11 @@ "version": "1.1.0", "description": "pear-rec is a cross platform screenshot, screen recording, audio recording, and video recording software.", "scripts": { - "start:desktop": "concurrently --names \"WEB,DESKTOP\" -c \"red,blue\" \"npm run dev:web\" \"wait-on tcp:9191 && pnpm run dev:desktop\"", + "start:desktop": "concurrently --names \"SERVER,WEB,DESKTOP\" -c \"red,blue,auto\" \"npm run dev:server\" \"wait-on tcp:9190 && npm run dev:web\" \"wait-on tcp:9191 && pnpm run dev:desktop\"", "dev:desktop": "pnpm run -C packages/desktop dev", - "build:desktop": "pnpm run -C packages/desktop build && pnpm run project:desktop && pnpm run -C packages/desktop build:win", - "project:desktop": "pnpm run -C packages/web build && node tools/copy-files-web2desktop.js", - "rebuild:server": "pnpm run -C packages/server rebuild && pnpm run -C packages/desktop rebuild", + "build:desktop": "pnpm run -C packages/desktop build && pnpm run copy:web && pnpm run copy:server && pnpm run -C packages/desktop build:win", + "copy:web": "pnpm run -C packages/web build && node tools/copy-files-web2desktop.js", + "copy:server": "pnpm run -C packages/server build && node tools/copy-files-server2desktop.js", "start:web": "concurrently --names \"SERVER,WEB\" -c \"red,auto\" \"npm run dev:server\" \"wait-on tcp:9190 && npm run dev:web\"", "dev:web": "pnpm run -C packages/web dev", "build:web": "concurrently -s \"pnpm run -C packages/server dev\" \"pnpm run project:web\"", diff --git a/packages/desktop/electron/main/contract.ts b/packages/desktop/electron/main/contract.ts index 126cfba2..c19a6bbf 100644 --- a/packages/desktop/electron/main/contract.ts +++ b/packages/desktop/electron/main/contract.ts @@ -11,7 +11,7 @@ export const VITE_API_URL = import.meta.env.VITE_API_URL; // export const WEB_URL = 'http://127.0.0.1:9191/'; // export const VITE_API_URL = 'http://127.0.0.1:9190/'; export const preload = path.join(__dirname, '../preload/index.js'); -export const serverPath = path.join(__dirname, '../server/index.js'); +export const serverPath = path.join(__dirname, '../server/mian.js'); export const DIST_ELECTRON = path.join(__dirname, '../'); export const DIST = path.join(DIST_ELECTRON, '../dist'); diff --git a/packages/desktop/electron/main/index.ts b/packages/desktop/electron/main/index.ts index eb328cac..a9b2d494 100644 --- a/packages/desktop/electron/main/index.ts +++ b/packages/desktop/electron/main/index.ts @@ -7,11 +7,11 @@ import { update } from './update'; import { registerFileProtocol } from './protocol'; import { registerGlobalShortcut, unregisterAllGlobalShortcut } from './globalShortcut'; import { initConfig, getConfig } from '@pear-rec/server/src/config'; -import { serverPath } from './contract'; +import { url, serverPath } from './contract'; import './ipcMain'; const appName = app.getPath('exe'); -const serverAppProcess = spawn(appName, [serverPath]); +const serverAppProcess = url || spawn(appName, [serverPath]); initConfig(); diff --git a/packages/server/.env b/packages/server/.env new file mode 100644 index 00000000..f47e5557 --- /dev/null +++ b/packages/server/.env @@ -0,0 +1 @@ +PORT=9190 diff --git a/packages/server/CHANGELOG.md b/packages/server/CHANGELOG.md index b42b68c1..1aba1e1f 100644 --- a/packages/server/CHANGELOG.md +++ b/packages/server/CHANGELOG.md @@ -1,5 +1,9 @@ # @pear-rec/server +## 1.3.1 + +fix: 接口代理、上传文件 + ## 1.3.0 refactor: 升级 nestjs 架构 diff --git a/packages/server/package.json b/packages/server/package.json index 2cba8ec2..4891f465 100644 --- a/packages/server/package.json +++ b/packages/server/package.json @@ -11,10 +11,12 @@ }, "dependencies": { "@nestjs/common": "^10.0.0", + "@nestjs/config": "^3.1.1", "@nestjs/core": "^10.0.0", "@nestjs/platform-express": "^10.0.0", "@nestjs/serve-static": "^4.0.0", "@nestjs/typeorm": "^10.0.1", + "http-proxy-middleware": "^2.0.6", "jsonfile": "^6.1.0", "multer": "^1.4.5-lts.1", "reflect-metadata": "^0.1.13", @@ -41,4 +43,4 @@ "tsconfig-paths": "^4.2.0", "typescript": "^5.1.3" } -} \ No newline at end of file +} diff --git a/packages/server/src/api/index.ts b/packages/server/src/api/index.ts deleted file mode 100644 index 82281654..00000000 --- a/packages/server/src/api/index.ts +++ /dev/null @@ -1,7 +0,0 @@ -// import { initBaiduProxy } from '../proxy/baidu'; -// import { initGoogleProxy } from '../proxy/google'; - -// export function initApi(app: Application) { -// initBaiduProxy(app); -// initGoogleProxy(app); -// } diff --git a/packages/server/src/api/local.ts b/packages/server/src/api/local.ts index 906179e8..66b9a88a 100644 --- a/packages/server/src/api/local.ts +++ b/packages/server/src/api/local.ts @@ -3,11 +3,11 @@ import multer from 'multer'; import { join, dirname } from 'node:path'; import { Application } from 'express'; import { exec } from 'child_process'; -import { getImgsByImgUrl, getAudiosByAudioUrl, getVideosByVideoUrl } from '../util/index'; -import { RecordsService } from '../records/records.service'; -import { UsersService } from '../users/users.service'; -import { SettingsService } from '../settings/settings.service'; -import { PEAR_FILES_PATH } from '../contract'; +// import { getImgsByImgUrl, getAudiosByAudioUrl, getVideosByVideoUrl } from '../util/index'; +// import { RecordsService } from '../records/records.service'; +// import { UsersService } from '../users/users.service'; +// import { SettingsService } from '../settings/settings.service'; +// import { PEAR_FILES_PATH } from '../contract'; // const usersService = new UsersService(); @@ -117,34 +117,34 @@ export function initLocalApi(app: Application) { } }); - app.get('/getImgs', async (req, res) => { - const { imgUrl, isElectron } = req.query as any; - const imgs = await getImgsByImgUrl(imgUrl, isElectron); - res.json({ code: 0, data: imgs }); - }); - - app.get('/getAudios', async (req, res) => { - const { audioUrl, isElectron } = req.query as any; - const audios = await getAudiosByAudioUrl(audioUrl, isElectron); - res.json({ code: 0, data: audios }); - }); - - app.get('/getVideos', async (req, res) => { - const { videoUrl, isElectron } = req.query as any; - const videos = await getVideosByVideoUrl(videoUrl, isElectron); - res.json({ code: 0, data: videos }); - }); - - app.get('/getFolder', async (req, res) => { - const folderPath = req.query.folderPath as string; - exec(`start "" "${folderPath}"`); - res.json({ code: 0 }); - }); - - app.get('/openFilePath', async (req, res) => { - const filePath = req.query.filePath as string; - const folderPath = dirname(filePath); - exec(`start "" "${folderPath}"`); - res.json({ code: 0 }); - }); + // app.get('/getImgs', async (req, res) => { + // const { imgUrl, isElectron } = req.query as any; + // const imgs = await getImgsByImgUrl(imgUrl, isElectron); + // res.json({ code: 0, data: imgs }); + // }); + + // app.get('/getAudios', async (req, res) => { + // const { audioUrl, isElectron } = req.query as any; + // const audios = await getAudiosByAudioUrl(audioUrl, isElectron); + // res.json({ code: 0, data: audios }); + // }); + + // app.get('/getVideos', async (req, res) => { + // const { videoUrl, isElectron } = req.query as any; + // const videos = await getVideosByVideoUrl(videoUrl, isElectron); + // res.json({ code: 0, data: videos }); + // }); + + // app.get('/getFolder', async (req, res) => { + // const folderPath = req.query.folderPath as string; + // exec(`start "" "${folderPath}"`); + // res.json({ code: 0 }); + // }); + + // app.get('/openFilePath', async (req, res) => { + // const filePath = req.query.filePath as string; + // const folderPath = dirname(filePath); + // exec(`start "" "${folderPath}"`); + // res.json({ code: 0 }); + // }); } diff --git a/packages/server/src/app/app.controller.ts b/packages/server/src/app/app.controller.ts index 15f0c470..51bd44ba 100644 --- a/packages/server/src/app/app.controller.ts +++ b/packages/server/src/app/app.controller.ts @@ -1,14 +1,6 @@ -import { - Controller, - Get, - Post, - StreamableFile, - Query, - UseInterceptors, - Res, - UploadedFile, -} from '@nestjs/common'; +import { Controller, Get, Post, StreamableFile, Query, Res } from '@nestjs/common'; import { join, dirname, basename, extname } from 'node:path'; +import { createProxyMiddleware, fixRequestBody } from 'http-proxy-middleware'; import { readdirSync, createReadStream, statSync } from 'node:fs'; import { FileInterceptor } from '@nestjs/platform-express'; import { CreateFileDto } from './dto/create-file.dto'; @@ -21,18 +13,6 @@ import type { Response } from 'express'; export class AppController { constructor(private readonly appService: AppService) {} - @Post('/upload/file') - // @UseInterceptors(FileInterceptor('fileName')) - async uploadFile(@UploadedFile() fileDto: CreateFileDto): Promise { - return this.appService.uploadFile(fileDto); - } - - @Get('/getFile') - getFile(@Query() query): StreamableFile { - const file = createReadStream(query.url); - return new StreamableFile(file); - } - @Get('/audio') getAudio(@Query() query, @Res({ passthrough: true }) res: Response): StreamableFile { const stream = createReadStream(query.url); @@ -86,7 +66,7 @@ export class AppController { ].includes(ext); } const port = process.env.PORT || 9190; - const protocol = `http://localhost:${port}/getFile?url=`; + const protocol = `http://localhost:${port}/file?url=`; if (isImgFile(filePath)) { filePath == imgUrl && (currentIndex = index); imgs.push({ diff --git a/packages/server/src/app/app.module.ts b/packages/server/src/app/app.module.ts index ef45ade6..68efc81b 100644 --- a/packages/server/src/app/app.module.ts +++ b/packages/server/src/app/app.module.ts @@ -1,5 +1,7 @@ import { join } from 'node:path'; -import { Module } from '@nestjs/common'; +import { Module, MiddlewareConsumer, NestModule } from '@nestjs/common'; +import { ConfigModule } from '@nestjs/config'; +import { MulterModule } from '@nestjs/platform-express'; import { APP_INTERCEPTOR, APP_FILTER } from '@nestjs/core'; import { ServeStaticModule } from '@nestjs/serve-static'; import { TypeOrmModule } from '@nestjs/typeorm'; @@ -8,15 +10,23 @@ import { Record } from '../records/entity/record.entity'; import { Setting } from '../settings/entity/setting.entity'; import { DB_PATH } from '../contract'; import { AppController } from './app.controller'; +import { FileController } from './file.controller'; import { AppService } from './app.service'; import { UsersModule } from '../users/users.module'; import { RecordsModule } from '../records/records.module'; import { SettingsModule } from '../settings/settings.module'; import { ResponseInterceptor } from '../util/response.interceptor'; import { AllExceptionsFilter } from '../util/exception.filter'; +import configuration from '../util/configuration'; +import { ProxyGoogle, ProxyBaidu } from '../util/proxy.middleware'; +import { UploadMiddleware } from '../util/upload.middleware'; @Module({ imports: [ + ConfigModule.forRoot({ + envFilePath: '.env', + load: [configuration], + }), ServeStaticModule.forRoot({ rootPath: join(__dirname, '../../', 'public'), }), @@ -26,14 +36,17 @@ import { AllExceptionsFilter } from '../util/exception.filter'; autoSave: true, entities: [User, Record, Setting], synchronize: true, - logging: true, + logging: false, logger: 'file', }), + MulterModule.registerAsync({ + useClass: UploadMiddleware, + }), UsersModule, RecordsModule, SettingsModule, ], - controllers: [AppController], + controllers: [AppController, FileController], providers: [ AppService, { @@ -46,4 +59,9 @@ import { AllExceptionsFilter } from '../util/exception.filter'; }, ], }) -export class AppModule {} +export class AppModule implements NestModule { + configure(consumer: MiddlewareConsumer) { + consumer.apply(ProxyBaidu).forRoutes('/apiBaidu'); + consumer.apply(ProxyGoogle).forRoutes('/apiGoogle'); + } +} diff --git a/packages/server/src/app/app.service.ts b/packages/server/src/app/app.service.ts index d1c487d4..2ed27d3f 100644 --- a/packages/server/src/app/app.service.ts +++ b/packages/server/src/app/app.service.ts @@ -1,5 +1,3 @@ -import * as fs from 'fs'; -import * as path from 'path'; import { Injectable } from '@nestjs/common'; import { CreateFileDto } from './dto/create-file.dto'; import { Record } from '../records/entity/record.entity'; @@ -17,8 +15,7 @@ export class AppService { return 'Hello World!'; } - async uploadFile(fileDto: CreateFileDto): Promise { - const userId = fileDto.userId; + async uploadFile(fileDto, userId: number): Promise { const user = await this.usersService.findOne(userId); let record = { filePath: fileDto.path, diff --git a/packages/server/src/app/file.controller.ts b/packages/server/src/app/file.controller.ts new file mode 100644 index 00000000..87a16de0 --- /dev/null +++ b/packages/server/src/app/file.controller.ts @@ -0,0 +1,35 @@ +import { + Controller, + Get, + Post, + StreamableFile, + Query, + Body, + UploadedFile, + UseInterceptors, +} from '@nestjs/common'; +import { createReadStream } from 'node:fs'; +import { FileInterceptor } from '@nestjs/platform-express'; +import { CreateFileDto } from './dto/create-file.dto'; +import { AppService } from './app.service'; +import { Record } from '../records/entity/record.entity'; + +@Controller('/file') +export class FileController { + constructor(private readonly appService: AppService) {} + + @Get('') + getFile(@Query() query): StreamableFile { + const file = createReadStream(query.url); + return new StreamableFile(file); + } + + @Post('/upload') + @UseInterceptors(FileInterceptor('file')) + async uploadFile( + @UploadedFile() file: Express.Multer.File, + @Body() createFileDto: CreateFileDto, + ): Promise { + return this.appService.uploadFile(file, createFileDto.userId); + } +} diff --git a/packages/server/src/contract/index.ts b/packages/server/src/contract/index.ts index 5728d41d..e02078f3 100644 --- a/packages/server/src/contract/index.ts +++ b/packages/server/src/contract/index.ts @@ -1,8 +1,6 @@ import { join } from 'node:path'; import { homedir } from 'node:os'; -export const PORT = process.env.PORT || 9190; - export const DOCS_PATH = join(homedir(), 'Documents'); export const PEAR_FILES_PATH = join(DOCS_PATH, 'Pear Files'); diff --git a/packages/server/src/main.ts b/packages/server/src/main.ts index 7629ff56..8db31888 100644 --- a/packages/server/src/main.ts +++ b/packages/server/src/main.ts @@ -1,47 +1,18 @@ -import * as fs from 'node:fs'; -import { join } from 'node:path'; import { NestFactory } from '@nestjs/core'; import { AppModule } from './app/app.module'; -import { initConfig, getConfig } from './config'; -import { PORT } from './contract'; -import * as multer from 'multer'; +import { initConfig } from './config'; +import { ConfigService } from '@nestjs/config'; async function bootstrap() { initConfig(); - const app = await NestFactory.create(AppModule, { cors: true, bodyParser: false }); - - const storage = multer.diskStorage({ - destination: async function (req, file, cb) { - const { type, userId } = req.body; - const config = getConfig(); - const user = config.user; - try { - const filePath = join(config?.filePath, `${user.uuid}/${type}`); - if (!fs.existsSync(filePath)) { - fs.mkdirSync(filePath, { recursive: true }); - } - cb(null, filePath); - } catch (err) { - console.log('saveFile err', err); - } - }, - filename: function (req, file, cb) { - const fileTypeMap = { - ss: 'png', - rs: 'webm', - ra: 'webm', - ei: 'png', - }; - const type = req.body.type; - const fileType = fileTypeMap[type] || 'webm'; - const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9); - const fileName = `${type}-${uniqueSuffix}.${fileType}`; - cb(null, fileName); - }, + const app = await NestFactory.create(AppModule, { + cors: true, + bodyParser: false, }); - app.use(multer({ storage }).single('file')); + const configService = app.get(ConfigService); + const PORT = configService.get('PORT'); await app.listen(PORT); diff --git a/packages/server/src/proxy/baidu.ts b/packages/server/src/proxy/baidu.ts deleted file mode 100644 index eae0a039..00000000 --- a/packages/server/src/proxy/baidu.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { Application, Request, Response } from "express"; -import { createProxyMiddleware, fixRequestBody } from "http-proxy-middleware"; - -export function initBaiduProxy(app: Application) { - app.use( - "/apiBaidu", - createProxyMiddleware({ - target: "https://graph.baidu.com/", - changeOrigin: true, - secure: false, - logLevel: "debug", - pathRewrite: { - "^/apiBaidu": "", - }, - }), - ); -} diff --git a/packages/server/src/proxy/google.ts b/packages/server/src/proxy/google.ts deleted file mode 100644 index f621b751..00000000 --- a/packages/server/src/proxy/google.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { Application, Request, Response } from "express"; -import { HttpsProxyAgent } from "https-proxy-agent"; -import { createProxyMiddleware, fixRequestBody } from "http-proxy-middleware"; - -export function initGoogleProxy(app: Application) { - app.use( - "/apiGoogle", - createProxyMiddleware({ - target: "https://lens.google.com", - changeOrigin: true, - secure: false, - logLevel: "debug", - onProxyReq: fixRequestBody, - agent: new HttpsProxyAgent("http://127.0.0.1:7890"), - pathRewrite: { - "^/apiGoogle": "", - }, - }), - ); -} diff --git a/packages/server/src/util/configuration.ts b/packages/server/src/util/configuration.ts new file mode 100644 index 00000000..9090f7e4 --- /dev/null +++ b/packages/server/src/util/configuration.ts @@ -0,0 +1,3 @@ +export default () => ({ + port: parseInt(process.env.PORT, 10) || 9190, +}); diff --git a/packages/server/src/util/exception.filter.ts b/packages/server/src/util/exception.filter.ts index 7a489a7b..841bb824 100644 --- a/packages/server/src/util/exception.filter.ts +++ b/packages/server/src/util/exception.filter.ts @@ -2,7 +2,7 @@ import { ExceptionFilter, Catch, ArgumentsHost, HttpException, HttpStatus } from @Catch() export class AllExceptionsFilter implements ExceptionFilter { - catch(exception: unknown, host: ArgumentsHost) { + catch(exception: any, host: ArgumentsHost) { const ctx = host.switchToHttp(); const response = ctx.getResponse(); diff --git a/packages/server/src/util/index.ts b/packages/server/src/util/index.ts deleted file mode 100644 index 9601f811..00000000 --- a/packages/server/src/util/index.ts +++ /dev/null @@ -1,125 +0,0 @@ -import fs from 'node:fs'; -import { join, dirname, extname, basename } from 'node:path'; - -function getProtocol(isElectron: boolean, type: string) { - const port = process.env.PORT || 9190; - const protocol = isElectron ? 'pearrec:///' : `http://localhost:${port}/${type}?url=`; - - return protocol; -} - -export function getImgsByImgUrl(imgUrl: string, isElectron: boolean) { - let imgs: any[] = []; - let index = 0; - let currentIndex = 0; - try { - const directoryPath = dirname(imgUrl); - const files = fs.readdirSync(directoryPath); // 读取目录内容 - files.forEach((file) => { - const filePath = join(directoryPath, file); - - if (isImgFile(filePath)) { - filePath == imgUrl && (currentIndex = index); - imgs.push({ - url: `${getProtocol(isElectron, 'getFile')}${filePath}`, - filePath: filePath, - index, - }); - index++; - } - }); - } catch (err) { - console.log('getImgsByImgUrl', err); - } - return { imgs, currentIndex }; -} - -function isImgFile(filePath: string): boolean { - const ext = extname(filePath).toLowerCase(); - return [ - '.jpg', - '.jpeg', - '.jfif', - '.pjpeg', - '.pjp', - '.png', - 'apng', - '.gif', - '.bmp', - '.avif', - '.webp', - '.ico', - ].includes(ext); -} - -export function getAudiosByAudioUrl(audioUrl: string, isElectron: boolean) { - const directoryPath = dirname(audioUrl); - const files = fs.readdirSync(directoryPath); // 读取目录内容 - let audios: any[] = []; - let index = 0; - files.forEach((file) => { - const filePath = join(directoryPath, file); - if (isAudioFile(filePath)) { - const fileName = basename(filePath); - if (filePath == audioUrl) { - audios.unshift({ - url: `${getProtocol(isElectron, 'audio')}${filePath}`, - name: fileName, - cover: './imgs/music.png', - }); - } else { - audios.push({ - url: `${getProtocol(isElectron, 'audio')}${filePath}`, - name: fileName, - cover: './imgs/music.png', - }); - } - index++; - } - }); - return audios; -} - -function isAudioFile(filePath: string): boolean { - const ext = extname(filePath).toLowerCase(); - return [ - '.mp3', - '.wav', - '.aac', - '.ogg', - '.flac', - '.aiff', - '.aif', - '.m4a', - '.alac', - '.ac3', - '.webm', - ].includes(ext); -} - -export function getVideosByVideoUrl(videoUrl: string, isElectron: boolean) { - const directoryPath = dirname(videoUrl); - const files = fs.readdirSync(directoryPath); - let videos: any[] = []; - let index = 0; - let currentIndex = 0; - files.forEach((file) => { - const filePath = join(directoryPath, file); - if (isVideoFile(filePath)) { - const fileName = basename(filePath); - filePath == videoUrl && (currentIndex = index); - videos.push({ - url: `${getProtocol(isElectron, 'video')}${filePath}`, - index, - name: fileName, - }); - index++; - } - }); - return { videos, currentIndex }; -} - -function isVideoFile(filePath: string): boolean { - const ext = extname(filePath).toLowerCase(); - return ['.mp4', '.mkv', '.avi', '.mov', '.wmv', '.webm'].includes(ext); -} diff --git a/packages/server/src/util/proxy.middleware.ts b/packages/server/src/util/proxy.middleware.ts new file mode 100644 index 00000000..21fe08a8 --- /dev/null +++ b/packages/server/src/util/proxy.middleware.ts @@ -0,0 +1,33 @@ +import { createProxyMiddleware, fixRequestBody } from 'http-proxy-middleware'; +import { NestMiddleware, Injectable } from '@nestjs/common'; +import { HttpsProxyAgent } from 'https-proxy-agent'; + +@Injectable() +export class ProxyBaidu implements NestMiddleware { + use(req: any, res: any, next: () => void) { + createProxyMiddleware('/apiBaidu', { + target: 'https://graph.baidu.com/', // 替换为你要代理的接口地址 + changeOrigin: true, + secure: false, + pathRewrite: { + '^/apiBaidu': '', // 如果接口地址有前缀,需替换为空字符串 + }, + })(req, res, next); + } +} + +@Injectable() +export class ProxyGoogle implements NestMiddleware { + use(req: any, res: any, next: () => void) { + createProxyMiddleware('/apiGoogle', { + target: 'https://lens.google.com', + changeOrigin: true, + secure: false, + onProxyReq: fixRequestBody, + agent: new HttpsProxyAgent('http://127.0.0.1:7890'), + pathRewrite: { + '^/apiGoogle': '', // 如果接口地址有前缀,需替换为空字符串 + }, + })(req, res, next); + } +} diff --git a/packages/server/src/util/upload.middleware.ts b/packages/server/src/util/upload.middleware.ts new file mode 100644 index 00000000..bc97ef99 --- /dev/null +++ b/packages/server/src/util/upload.middleware.ts @@ -0,0 +1,44 @@ +import { Injectable } from '@nestjs/common'; +import { MulterModuleOptions, MulterOptionsFactory } from '@nestjs/platform-express'; +import { diskStorage } from 'multer'; +import { join } from 'node:path'; +import { existsSync, mkdirSync } from 'node:fs'; +import { getConfig } from '../config'; + +@Injectable() +export class UploadMiddleware implements MulterOptionsFactory { + createMulterOptions(): MulterModuleOptions { + return { + storage: diskStorage({ + destination: async function (req, file, cb) { + console.log(1234); + const { type, userId } = req.body; + const config = getConfig(); + const user = config.user; + try { + const filePath = join(config?.filePath, `${user.uuid}/${type}`); + if (!existsSync(filePath)) { + mkdirSync(filePath, { recursive: true }); + } + cb(null, filePath); + } catch (err) { + console.log('saveFile err', err); + } + }, + filename: function (req, file, cb) { + const fileTypeMap = { + ss: 'png', + rs: 'webm', + ra: 'webm', + ei: 'png', + }; + const type = req.body.type; + const fileType = fileTypeMap[type] || 'webm'; + const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9); + const fileName = `${type}-${uniqueSuffix}.${fileType}`; + cb(null, fileName); + }, + }), + }; + } +} diff --git a/packages/web/src/api/index.ts b/packages/web/src/api/index.ts index a8bc4d78..167f8b50 100644 --- a/packages/web/src/api/index.ts +++ b/packages/web/src/api/index.ts @@ -4,7 +4,7 @@ export function useApi() { return { saveFile: (formData) => { return request({ - url: `/upload/file`, + url: `/file/upload`, method: 'post', headers: { 'Content-Type': 'multipart/form-data', @@ -26,7 +26,7 @@ export function useApi() { }, getFile: (url) => { return request({ - url: `/getFile?url=${url}`, + url: `/file?url=${url}`, method: 'get', }); }, diff --git a/tools/copy-files-server2desktop.js b/tools/copy-files-server2desktop.js new file mode 100644 index 00000000..c40ea68c --- /dev/null +++ b/tools/copy-files-server2desktop.js @@ -0,0 +1,27 @@ +const fs = require('fs-extra'); +const { rimraf, rimrafSync } = require('rimraf'); + +const copyFiles = async () => { + try { + await fs.copy('./packages/server/dist', './packages/desktop/dist-electron/server'); + console.log('Server files copied over successfully'); + } catch (err) { + console.error(err); + } +}; + +function deleteFolderFiles() { + const folderPath = './packages/desktop/dist-electron/server'; + + rimraf + .rimraf(folderPath) + .then(() => { + console.log('Desktop files delete successfully'); + copyFiles(); + }) + .catch((err) => { + console.error('deleteFolderFiles', err); + }); +} + +deleteFolderFiles();