Skip to content

Commit

Permalink
fix: 接口代理、上传文件
Browse files Browse the repository at this point in the history
  • Loading branch information
027xiguapi committed Dec 14, 2023
1 parent a5d04e6 commit 1985f79
Show file tree
Hide file tree
Showing 23 changed files with 228 additions and 284 deletions.
8 changes: 4 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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\"",
Expand Down
2 changes: 1 addition & 1 deletion packages/desktop/electron/main/contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');

Expand Down
4 changes: 2 additions & 2 deletions packages/desktop/electron/main/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand Down
1 change: 1 addition & 0 deletions packages/server/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
PORT=9190
4 changes: 4 additions & 0 deletions packages/server/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# @pear-rec/server

## 1.3.1

fix: 接口代理、上传文件

## 1.3.0

refactor: 升级 nestjs 架构
Expand Down
4 changes: 3 additions & 1 deletion packages/server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -41,4 +43,4 @@
"tsconfig-paths": "^4.2.0",
"typescript": "^5.1.3"
}
}
}
7 changes: 0 additions & 7 deletions packages/server/src/api/index.ts

This file was deleted.

70 changes: 35 additions & 35 deletions packages/server/src/api/local.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand Down Expand Up @@ -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 });
// });
}
26 changes: 3 additions & 23 deletions packages/server/src/app/app.controller.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -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<Record> {
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);
Expand Down Expand Up @@ -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({
Expand Down
26 changes: 22 additions & 4 deletions packages/server/src/app/app.module.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -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'),
}),
Expand All @@ -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,
{
Expand All @@ -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');
}
}
5 changes: 1 addition & 4 deletions packages/server/src/app/app.service.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -17,8 +15,7 @@ export class AppService {
return 'Hello World!';
}

async uploadFile(fileDto: CreateFileDto): Promise<Record> {
const userId = fileDto.userId;
async uploadFile(fileDto, userId: number): Promise<Record> {
const user = await this.usersService.findOne(userId);
let record = {
filePath: fileDto.path,
Expand Down
35 changes: 35 additions & 0 deletions packages/server/src/app/file.controller.ts
Original file line number Diff line number Diff line change
@@ -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<Record> {
return this.appService.uploadFile(file, createFileDto.userId);
}
}
2 changes: 0 additions & 2 deletions packages/server/src/contract/index.ts
Original file line number Diff line number Diff line change
@@ -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');
Expand Down
43 changes: 7 additions & 36 deletions packages/server/src/main.ts
Original file line number Diff line number Diff line change
@@ -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);

Expand Down
Loading

0 comments on commit 1985f79

Please sign in to comment.