mirror of
https://github.com/vastxie/99AI.git
synced 2025-11-13 04:03:45 +08:00
v3.3.3
This commit is contained in:
25
dist/modules/app/app.controller.js
vendored
25
dist/modules/app/app.controller.js
vendored
@@ -55,6 +55,9 @@ let AppController = class AppController {
|
||||
appList(req, query) {
|
||||
return this.appService.appList(req, query);
|
||||
}
|
||||
appSystemList() {
|
||||
return this.appService.appSystemList();
|
||||
}
|
||||
list(req, query) {
|
||||
return this.appService.frontAppList(req, query);
|
||||
}
|
||||
@@ -67,6 +70,9 @@ let AppController = class AppController {
|
||||
updateApp(body) {
|
||||
return this.appService.updateApp(body);
|
||||
}
|
||||
updateSystemApp(body) {
|
||||
return this.appService.updateSystemApp(body);
|
||||
}
|
||||
delApp(body) {
|
||||
return this.appService.delApp(body);
|
||||
}
|
||||
@@ -152,6 +158,15 @@ __decorate([
|
||||
__metadata("design:paramtypes", [Object, queryApp_dto_1.QuerAppDto]),
|
||||
__metadata("design:returntype", void 0)
|
||||
], AppController.prototype, "appList", null);
|
||||
__decorate([
|
||||
(0, common_1.Get)('querySystemApp'),
|
||||
(0, swagger_1.ApiOperation)({ summary: '获取系统App列表' }),
|
||||
(0, common_1.UseGuards)(adminAuth_guard_1.AdminAuthGuard),
|
||||
(0, swagger_1.ApiBearerAuth)(),
|
||||
__metadata("design:type", Function),
|
||||
__metadata("design:paramtypes", []),
|
||||
__metadata("design:returntype", void 0)
|
||||
], AppController.prototype, "appSystemList", null);
|
||||
__decorate([
|
||||
(0, common_1.Get)('list'),
|
||||
(0, swagger_1.ApiOperation)({ summary: '客户端获取App' }),
|
||||
@@ -192,6 +207,16 @@ __decorate([
|
||||
__metadata("design:paramtypes", [updateApp_dto_1.UpdateAppDto]),
|
||||
__metadata("design:returntype", void 0)
|
||||
], AppController.prototype, "updateApp", null);
|
||||
__decorate([
|
||||
(0, common_1.Post)('updateSystemApp'),
|
||||
(0, swagger_1.ApiOperation)({ summary: '修改系统App' }),
|
||||
(0, common_1.UseGuards)(superAuth_guard_1.SuperAuthGuard),
|
||||
(0, swagger_1.ApiBearerAuth)(),
|
||||
__param(0, (0, common_1.Body)()),
|
||||
__metadata("design:type", Function),
|
||||
__metadata("design:paramtypes", [Object]),
|
||||
__metadata("design:returntype", void 0)
|
||||
], AppController.prototype, "updateSystemApp", null);
|
||||
__decorate([
|
||||
(0, common_1.Post)('delApp'),
|
||||
(0, swagger_1.ApiOperation)({ summary: '删除App' }),
|
||||
|
||||
24
dist/modules/app/app.entity.js
vendored
24
dist/modules/app/app.entity.js
vendored
@@ -10,8 +10,8 @@ var __metadata = (this && this.__metadata) || function (k, v) {
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.AppEntity = void 0;
|
||||
const typeorm_1 = require("typeorm");
|
||||
const baseEntity_1 = require("../../common/entity/baseEntity");
|
||||
const typeorm_1 = require("typeorm");
|
||||
let AppEntity = class AppEntity extends baseEntity_1.BaseEntity {
|
||||
};
|
||||
__decorate([
|
||||
@@ -31,7 +31,7 @@ __decorate([
|
||||
__metadata("design:type", String)
|
||||
], AppEntity.prototype, "preset", void 0);
|
||||
__decorate([
|
||||
(0, typeorm_1.Column)({ comment: 'App应用封面图片', nullable: true }),
|
||||
(0, typeorm_1.Column)({ comment: 'App应用封面图片', nullable: true, type: 'text' }),
|
||||
__metadata("design:type", String)
|
||||
], AppEntity.prototype, "coverImg", void 0);
|
||||
__decorate([
|
||||
@@ -50,6 +50,22 @@ __decorate([
|
||||
(0, typeorm_1.Column)({ comment: 'App应用角色 system user', default: 'system' }),
|
||||
__metadata("design:type", String)
|
||||
], AppEntity.prototype, "role", void 0);
|
||||
__decorate([
|
||||
(0, typeorm_1.Column)({ comment: 'App应用是否是GPTs', default: '0' }),
|
||||
__metadata("design:type", Number)
|
||||
], AppEntity.prototype, "isGPTs", void 0);
|
||||
__decorate([
|
||||
(0, typeorm_1.Column)({ comment: 'App应用是否是固定使用模型', default: '0' }),
|
||||
__metadata("design:type", Number)
|
||||
], AppEntity.prototype, "isFixedModel", void 0);
|
||||
__decorate([
|
||||
(0, typeorm_1.Column)({ comment: 'App应用使用的模型', type: 'text' }),
|
||||
__metadata("design:type", String)
|
||||
], AppEntity.prototype, "appModel", void 0);
|
||||
__decorate([
|
||||
(0, typeorm_1.Column)({ comment: 'GPTs 的调用ID', default: '' }),
|
||||
__metadata("design:type", String)
|
||||
], AppEntity.prototype, "gizmoID", void 0);
|
||||
__decorate([
|
||||
(0, typeorm_1.Column)({ comment: 'App是否共享到应用广场', default: false }),
|
||||
__metadata("design:type", Boolean)
|
||||
@@ -58,6 +74,10 @@ __decorate([
|
||||
(0, typeorm_1.Column)({ comment: '用户Id', nullable: true }),
|
||||
__metadata("design:type", Number)
|
||||
], AppEntity.prototype, "userId", void 0);
|
||||
__decorate([
|
||||
(0, typeorm_1.Column)({ comment: '是否系统预留', default: false, nullable: true }),
|
||||
__metadata("design:type", Boolean)
|
||||
], AppEntity.prototype, "isSystemReserved", void 0);
|
||||
AppEntity = __decorate([
|
||||
(0, typeorm_1.Entity)({ name: 'app' })
|
||||
], AppEntity);
|
||||
|
||||
110
dist/modules/app/app.service.js
vendored
110
dist/modules/app/app.service.js
vendored
@@ -14,10 +14,10 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.AppService = void 0;
|
||||
const common_1 = require("@nestjs/common");
|
||||
const appCats_entity_1 = require("./appCats.entity");
|
||||
const typeorm_1 = require("typeorm");
|
||||
const typeorm_2 = require("@nestjs/typeorm");
|
||||
const typeorm_1 = require("@nestjs/typeorm");
|
||||
const typeorm_2 = require("typeorm");
|
||||
const app_entity_1 = require("./app.entity");
|
||||
const appCats_entity_1 = require("./appCats.entity");
|
||||
const userApps_entity_1 = require("./userApps.entity");
|
||||
let AppService = class AppService {
|
||||
constructor(appCatsEntity, appEntity, userAppsEntity) {
|
||||
@@ -50,7 +50,7 @@ let AppService = class AppService {
|
||||
}
|
||||
async updateAppCats(body) {
|
||||
const { id, name } = body;
|
||||
const c = await this.appCatsEntity.findOne({ where: { name, id: (0, typeorm_1.Not)(id) } });
|
||||
const c = await this.appCatsEntity.findOne({ where: { name, id: (0, typeorm_2.Not)(id) } });
|
||||
if (c) {
|
||||
throw new common_1.HttpException('该分类名称已存在!', common_1.HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
@@ -65,18 +65,21 @@ let AppService = class AppService {
|
||||
throw new common_1.HttpException('缺失必要参数!', common_1.HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
const app = await this.appEntity.findOne({ where: { id } });
|
||||
const { demoData: demo, coverImg, des, name } = app;
|
||||
const { demoData: demo, coverImg, des, name, isFixedModel, isGPTs, appModel } = app;
|
||||
return {
|
||||
demoData: demo ? demo.split('\n') : [],
|
||||
coverImg,
|
||||
des,
|
||||
name,
|
||||
isGPTs,
|
||||
isFixedModel,
|
||||
appModel,
|
||||
};
|
||||
}
|
||||
async appCatsList(query) {
|
||||
const { page = 1, size = 10, name, status } = query;
|
||||
const where = {};
|
||||
name && (where.name = (0, typeorm_1.Like)(`%${name}%`));
|
||||
name && (where.name = (0, typeorm_2.Like)(`%${name}%`));
|
||||
[0, 1, '0', '1'].includes(status) && (where.status = status);
|
||||
const [rows, count] = await this.appCatsEntity.findAndCount({
|
||||
where,
|
||||
@@ -85,7 +88,7 @@ let AppService = class AppService {
|
||||
take: size,
|
||||
});
|
||||
const catIds = rows.map((item) => item.id);
|
||||
const apps = await this.appEntity.find({ where: { catId: (0, typeorm_1.In)(catIds) } });
|
||||
const apps = await this.appEntity.find({ where: { catId: (0, typeorm_2.In)(catIds) } });
|
||||
const appCountMap = {};
|
||||
apps.forEach((item) => {
|
||||
if (appCountMap[item.catId]) {
|
||||
@@ -101,8 +104,8 @@ let AppService = class AppService {
|
||||
async appList(req, query, orderKey = 'id') {
|
||||
var _a;
|
||||
const { page = 1, size = 10, name, status, catId, role } = query;
|
||||
const where = {};
|
||||
name && (where.name = (0, typeorm_1.Like)(`%${name}%`));
|
||||
const where = { isSystemReserved: 0 };
|
||||
name && (where.name = (0, typeorm_2.Like)(`%${name}%`));
|
||||
catId && (where.catId = catId);
|
||||
role && (where.role = role);
|
||||
status && (where.status = status);
|
||||
@@ -113,7 +116,7 @@ let AppService = class AppService {
|
||||
take: size,
|
||||
});
|
||||
const catIds = rows.map((item) => item.catId);
|
||||
const cats = await this.appCatsEntity.find({ where: { id: (0, typeorm_1.In)(catIds) } });
|
||||
const cats = await this.appCatsEntity.find({ where: { id: (0, typeorm_2.In)(catIds) } });
|
||||
rows.forEach((item) => {
|
||||
const cat = cats.find((c) => c.id === item.catId);
|
||||
item.catName = cat ? cat.name : '';
|
||||
@@ -125,12 +128,20 @@ let AppService = class AppService {
|
||||
}
|
||||
return { rows, count };
|
||||
}
|
||||
async appSystemList() {
|
||||
const where = { isSystemReserved: 1 };
|
||||
const [rows, count] = await this.appEntity.findAndCount({
|
||||
where,
|
||||
order: { id: 'DESC' },
|
||||
});
|
||||
return { rows, count };
|
||||
}
|
||||
async frontAppList(req, query, orderKey = 'id') {
|
||||
var _a;
|
||||
const { page = 1, size = 1000, name, catId, role } = query;
|
||||
const where = [
|
||||
{ status: (0, typeorm_1.In)([1, 4]), userId: (0, typeorm_1.IsNull)(), public: false },
|
||||
{ userId: (0, typeorm_1.MoreThan)(0), public: true },
|
||||
{ status: (0, typeorm_2.In)([1, 4]), userId: (0, typeorm_2.IsNull)(), public: false, isSystemReserved: 0 },
|
||||
{ userId: (0, typeorm_2.MoreThan)(0), public: true },
|
||||
];
|
||||
const [rows, count] = await this.appEntity.findAndCount({
|
||||
where,
|
||||
@@ -139,7 +150,7 @@ let AppService = class AppService {
|
||||
take: size,
|
||||
});
|
||||
const catIds = rows.map((item) => item.catId);
|
||||
const cats = await this.appCatsEntity.find({ where: { id: (0, typeorm_1.In)(catIds) } });
|
||||
const cats = await this.appCatsEntity.find({ where: { id: (0, typeorm_2.In)(catIds) } });
|
||||
rows.forEach((item) => {
|
||||
const cat = cats.find((c) => c.id === item.catId);
|
||||
item.catName = cat ? cat.name : '';
|
||||
@@ -198,7 +209,7 @@ let AppService = class AppService {
|
||||
}
|
||||
async updateApp(body) {
|
||||
const { id, name, catId, status } = body;
|
||||
const a = await this.appEntity.findOne({ where: { name, id: (0, typeorm_1.Not)(id) } });
|
||||
const a = await this.appEntity.findOne({ where: { name, id: (0, typeorm_2.Not)(id) } });
|
||||
if (a) {
|
||||
throw new common_1.HttpException('该应用名称已存在!', common_1.HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
@@ -215,6 +226,22 @@ let AppService = class AppService {
|
||||
return '修改App信息成功';
|
||||
throw new common_1.HttpException('修改App信息失败!', common_1.HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
async updateSystemApp(body) {
|
||||
const { id, name } = body;
|
||||
common_1.Logger.log(`尝试更新应用: ${name} (ID: ${id})`);
|
||||
const existingApp = await this.appEntity.findOne({ where: { name, id: (0, typeorm_2.Not)(id) } });
|
||||
if (existingApp) {
|
||||
common_1.Logger.warn(`应用名称已存在:${name}`);
|
||||
throw new common_1.HttpException('该应用名称已存在!', common_1.HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
const res = await this.appEntity.update({ id }, body);
|
||||
if (res.affected > 0) {
|
||||
common_1.Logger.log(`修改系统应用信息成功: ${name}`);
|
||||
return '修改系统应用信息成功';
|
||||
}
|
||||
common_1.Logger.error(`修改系统应用信息失败:${name}`);
|
||||
throw new common_1.HttpException('修改系统应用信息失败!', common_1.HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
async delApp(body) {
|
||||
const { id } = body;
|
||||
const a = await this.appEntity.findOne({ where: { id } });
|
||||
@@ -277,38 +304,45 @@ let AppService = class AppService {
|
||||
const { id, role: appRole, catId } = app;
|
||||
const collectInfo = { userId, appId: id, catId, appRole, public: true, status: 1 };
|
||||
await this.userAppsEntity.save(collectInfo);
|
||||
return '已将应用加入到我的个人工作台!';
|
||||
return '已将应用加入到我的收藏!';
|
||||
}
|
||||
async mineApps(req, query = { page: 1, size: 30 }) {
|
||||
const { id } = req.user;
|
||||
const { page = 1, size = 30 } = query;
|
||||
const [rows, count] = await this.userAppsEntity.findAndCount({
|
||||
where: { userId: id, status: (0, typeorm_1.In)([1, 3, 4, 5]) },
|
||||
order: { id: 'DESC' },
|
||||
skip: (page - 1) * size,
|
||||
take: size,
|
||||
});
|
||||
const appIds = rows.map((item) => item.appId);
|
||||
const appsInfo = await this.appEntity.find({ where: { id: (0, typeorm_1.In)(appIds) } });
|
||||
rows.forEach((item) => {
|
||||
const app = appsInfo.find((c) => c.id === item.appId);
|
||||
item.appName = app ? app.name : '';
|
||||
item.appRole = app ? app.role : '';
|
||||
item.appDes = app ? app.des : '';
|
||||
item.coverImg = app ? app.coverImg : '';
|
||||
item.demoData = app ? app.demoData : '';
|
||||
item.preset = app.userId === id ? app.preset : '******';
|
||||
});
|
||||
let rows, count;
|
||||
try {
|
||||
[rows, count] = await this.userAppsEntity.findAndCount({
|
||||
where: { userId: id, status: (0, typeorm_2.In)([1, 3, 4, 5]) },
|
||||
order: { id: 'DESC' },
|
||||
skip: (page - 1) * size,
|
||||
take: size,
|
||||
});
|
||||
const appIds = rows.map((item) => item.appId);
|
||||
const appsInfo = await this.appEntity.find({ where: { id: (0, typeorm_2.In)(appIds) } });
|
||||
rows.forEach((item) => {
|
||||
const app = appsInfo.find((c) => c.id === item.appId);
|
||||
item.appName = app ? app.name : '未知';
|
||||
item.appRole = app ? app.role : '未知';
|
||||
item.appDes = app ? app.des : '未知';
|
||||
item.coverImg = app ? app.coverImg : '未知';
|
||||
item.demoData = app ? app.demoData : '未知';
|
||||
item.preset = app.userId === id ? app.preset : '******';
|
||||
});
|
||||
}
|
||||
catch (error) {
|
||||
console.error(`处理用户ID: ${id} 的mineApps请求时发生错误`, error);
|
||||
throw error;
|
||||
}
|
||||
return { rows, count };
|
||||
}
|
||||
};
|
||||
AppService = __decorate([
|
||||
(0, common_1.Injectable)(),
|
||||
__param(0, (0, typeorm_2.InjectRepository)(appCats_entity_1.AppCatsEntity)),
|
||||
__param(1, (0, typeorm_2.InjectRepository)(app_entity_1.AppEntity)),
|
||||
__param(2, (0, typeorm_2.InjectRepository)(userApps_entity_1.UserAppsEntity)),
|
||||
__metadata("design:paramtypes", [typeorm_1.Repository,
|
||||
typeorm_1.Repository,
|
||||
typeorm_1.Repository])
|
||||
__param(0, (0, typeorm_1.InjectRepository)(appCats_entity_1.AppCatsEntity)),
|
||||
__param(1, (0, typeorm_1.InjectRepository)(app_entity_1.AppEntity)),
|
||||
__param(2, (0, typeorm_1.InjectRepository)(userApps_entity_1.UserAppsEntity)),
|
||||
__metadata("design:paramtypes", [typeorm_2.Repository,
|
||||
typeorm_2.Repository,
|
||||
typeorm_2.Repository])
|
||||
], AppService);
|
||||
exports.AppService = AppService;
|
||||
|
||||
10
dist/modules/app/dto/createApp.dto.js
vendored
10
dist/modules/app/dto/createApp.dto.js
vendored
@@ -38,6 +38,16 @@ __decorate([
|
||||
(0, class_validator_1.IsOptional)(),
|
||||
__metadata("design:type", String)
|
||||
], CreateAppDto.prototype, "preset", void 0);
|
||||
__decorate([
|
||||
(0, swagger_1.ApiProperty)({ example: 'GPTs 的调用ID', description: 'GPTs 使用的 ID', required: false }),
|
||||
(0, class_validator_1.IsOptional)(),
|
||||
__metadata("design:type", String)
|
||||
], CreateAppDto.prototype, "gizmoID", void 0);
|
||||
__decorate([
|
||||
(0, swagger_1.ApiProperty)({ description: '是否GPTs', required: false }),
|
||||
(0, class_validator_1.IsOptional)(),
|
||||
__metadata("design:type", Number)
|
||||
], CreateAppDto.prototype, "isGPTs", void 0);
|
||||
__decorate([
|
||||
(0, swagger_1.ApiProperty)({ example: 'https://xxxx.png', description: '套餐封面图片', required: false }),
|
||||
(0, class_validator_1.IsOptional)(),
|
||||
|
||||
89
dist/modules/auth/auth.controller.js
vendored
89
dist/modules/auth/auth.controller.js
vendored
@@ -13,18 +13,13 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.AuthController = void 0;
|
||||
const verifyCode_dto_1 = require("./../verification/dto/verifyCode.dto");
|
||||
const authLogin_dto_1 = require("./dto/authLogin.dto");
|
||||
const common_1 = require("@nestjs/common");
|
||||
const jwtAuth_guard_1 = require("../../common/auth/jwtAuth.guard");
|
||||
const auth_service_1 = require("./auth.service");
|
||||
const common_1 = require("@nestjs/common");
|
||||
const swagger_1 = require("@nestjs/swagger");
|
||||
const authRegister_dto_1 = require("./dto/authRegister.dto");
|
||||
const updatePassword_dto_1 = require("./dto/updatePassword.dto");
|
||||
const auth_service_1 = require("./auth.service");
|
||||
const authLogin_dto_1 = require("./dto/authLogin.dto");
|
||||
const updatePassByOther_dto_1 = require("./dto/updatePassByOther.dto");
|
||||
const sendPhoneCode_dto_1 = require("./dto/sendPhoneCode.dto");
|
||||
const userRegisterByPhone_dto_1 = require("./dto/userRegisterByPhone.dto");
|
||||
const loginByPhone_dt_1 = require("./dto/loginByPhone.dt");
|
||||
const updatePassword_dto_1 = require("./dto/updatePassword.dto");
|
||||
let AuthController = class AuthController {
|
||||
constructor(authService) {
|
||||
this.authService = authService;
|
||||
@@ -32,15 +27,9 @@ let AuthController = class AuthController {
|
||||
async register(body, req) {
|
||||
return await this.authService.register(body, req);
|
||||
}
|
||||
async registerByPhone(body, req) {
|
||||
return await this.authService.registerByPhone(body, req);
|
||||
}
|
||||
async login(body, req) {
|
||||
return this.authService.login(body, req);
|
||||
}
|
||||
async loginByPhone(body, req) {
|
||||
return this.authService.loginByPhone(body, req);
|
||||
}
|
||||
async updatePassword(req, body) {
|
||||
return this.authService.updatePassword(req, body);
|
||||
}
|
||||
@@ -50,22 +39,11 @@ let AuthController = class AuthController {
|
||||
async getInfo(req) {
|
||||
return this.authService.getInfo(req);
|
||||
}
|
||||
async activateAccount(parmas, res) {
|
||||
return this.authService.activateAccount(parmas, res);
|
||||
}
|
||||
async registerSuccess(parmas) {
|
||||
const { username, id, email, teamName, registerSuccessEmailTitle, registerSuccessEmailTeamName, registerSuccessEmaileAppend } = parmas;
|
||||
return { username, id, email, teamName, registerSuccessEmailTitle, registerSuccessEmailTeamName, registerSuccessEmaileAppend };
|
||||
}
|
||||
async registerError(parmas) {
|
||||
const { message, teamName, registerFailEmailTitle, registerFailEmailTeamName } = parmas;
|
||||
return { message, teamName, registerFailEmailTitle, registerFailEmailTeamName };
|
||||
}
|
||||
async captcha(parmas) {
|
||||
return this.authService.captcha(parmas);
|
||||
}
|
||||
async sendPhoneCode(parmas) {
|
||||
return this.authService.sendPhoneCode(parmas);
|
||||
async sendCode(parmas) {
|
||||
return this.authService.sendCode(parmas);
|
||||
}
|
||||
};
|
||||
__decorate([
|
||||
@@ -74,18 +52,9 @@ __decorate([
|
||||
__param(0, (0, common_1.Body)()),
|
||||
__param(1, (0, common_1.Req)()),
|
||||
__metadata("design:type", Function),
|
||||
__metadata("design:paramtypes", [authRegister_dto_1.UserRegisterDto, Object]),
|
||||
__metadata("design:paramtypes", [Object, Object]),
|
||||
__metadata("design:returntype", Promise)
|
||||
], AuthController.prototype, "register", null);
|
||||
__decorate([
|
||||
(0, common_1.Post)('registerByPhone'),
|
||||
(0, swagger_1.ApiOperation)({ summary: '用户通过手机号注册' }),
|
||||
__param(0, (0, common_1.Body)()),
|
||||
__param(1, (0, common_1.Req)()),
|
||||
__metadata("design:type", Function),
|
||||
__metadata("design:paramtypes", [userRegisterByPhone_dto_1.UserRegisterByPhoneDto, Object]),
|
||||
__metadata("design:returntype", Promise)
|
||||
], AuthController.prototype, "registerByPhone", null);
|
||||
__decorate([
|
||||
(0, common_1.Post)('login'),
|
||||
(0, swagger_1.ApiOperation)({ summary: '用户登录' }),
|
||||
@@ -95,15 +64,6 @@ __decorate([
|
||||
__metadata("design:paramtypes", [authLogin_dto_1.UserLoginDto, Object]),
|
||||
__metadata("design:returntype", Promise)
|
||||
], AuthController.prototype, "login", null);
|
||||
__decorate([
|
||||
(0, common_1.Post)('loginByPhone'),
|
||||
(0, swagger_1.ApiOperation)({ summary: '用户手机号登录' }),
|
||||
__param(0, (0, common_1.Body)()),
|
||||
__param(1, (0, common_1.Req)()),
|
||||
__metadata("design:type", Function),
|
||||
__metadata("design:paramtypes", [loginByPhone_dt_1.LoginByPhoneDto, Object]),
|
||||
__metadata("design:returntype", Promise)
|
||||
], AuthController.prototype, "loginByPhone", null);
|
||||
__decorate([
|
||||
(0, common_1.Post)('updatePassword'),
|
||||
(0, swagger_1.ApiOperation)({ summary: '用户更改密码' }),
|
||||
@@ -136,33 +96,6 @@ __decorate([
|
||||
__metadata("design:paramtypes", [Object]),
|
||||
__metadata("design:returntype", Promise)
|
||||
], AuthController.prototype, "getInfo", null);
|
||||
__decorate([
|
||||
(0, common_1.Get)('activateAccount'),
|
||||
(0, swagger_1.ApiOperation)({ summary: '账户激活' }),
|
||||
__param(0, (0, common_1.Query)()),
|
||||
__param(1, (0, common_1.Res)()),
|
||||
__metadata("design:type", Function),
|
||||
__metadata("design:paramtypes", [verifyCode_dto_1.VerifyCodeDto, Object]),
|
||||
__metadata("design:returntype", Promise)
|
||||
], AuthController.prototype, "activateAccount", null);
|
||||
__decorate([
|
||||
(0, common_1.Get)('registerSuccess'),
|
||||
(0, swagger_1.ApiOperation)({ summary: '注册成功页面' }),
|
||||
(0, common_1.Render)('registerSuccess'),
|
||||
__param(0, (0, common_1.Query)()),
|
||||
__metadata("design:type", Function),
|
||||
__metadata("design:paramtypes", [Object]),
|
||||
__metadata("design:returntype", Promise)
|
||||
], AuthController.prototype, "registerSuccess", null);
|
||||
__decorate([
|
||||
(0, common_1.Get)('registerError'),
|
||||
(0, swagger_1.ApiOperation)({ summary: '注册失败页面' }),
|
||||
(0, common_1.Render)('registerError'),
|
||||
__param(0, (0, common_1.Query)()),
|
||||
__metadata("design:type", Function),
|
||||
__metadata("design:paramtypes", [Object]),
|
||||
__metadata("design:returntype", Promise)
|
||||
], AuthController.prototype, "registerError", null);
|
||||
__decorate([
|
||||
(0, common_1.Post)('captcha'),
|
||||
(0, swagger_1.ApiOperation)({ summary: '获取一个图形验证码' }),
|
||||
@@ -172,13 +105,13 @@ __decorate([
|
||||
__metadata("design:returntype", Promise)
|
||||
], AuthController.prototype, "captcha", null);
|
||||
__decorate([
|
||||
(0, common_1.Post)('sendPhoneCode'),
|
||||
(0, swagger_1.ApiOperation)({ summary: '发送手机验证码' }),
|
||||
(0, common_1.Post)('sendCode'),
|
||||
(0, swagger_1.ApiOperation)({ summary: '发送验证码' }),
|
||||
__param(0, (0, common_1.Body)()),
|
||||
__metadata("design:type", Function),
|
||||
__metadata("design:paramtypes", [sendPhoneCode_dto_1.SendPhoneCodeDto]),
|
||||
__metadata("design:paramtypes", [Object]),
|
||||
__metadata("design:returntype", Promise)
|
||||
], AuthController.prototype, "sendPhoneCode", null);
|
||||
], AuthController.prototype, "sendCode", null);
|
||||
AuthController = __decorate([
|
||||
(0, swagger_1.ApiTags)('auth'),
|
||||
(0, common_1.Controller)('auth'),
|
||||
|
||||
42
dist/modules/auth/auth.module.js
vendored
42
dist/modules/auth/auth.module.js
vendored
@@ -7,34 +7,34 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.AuthModule = void 0;
|
||||
const verifycation_entity_1 = require("./../verification/verifycation.entity");
|
||||
const typeorm_1 = require("@nestjs/typeorm");
|
||||
const verification_service_1 = require("./../verification/verification.service");
|
||||
const mailer_service_1 = require("../mailer/mailer.service");
|
||||
const nestjs_config_1 = require("nestjs-config");
|
||||
const auth_controller_1 = require("./auth.controller");
|
||||
const common_1 = require("@nestjs/common");
|
||||
const auth_service_1 = require("./auth.service");
|
||||
const user_module_1 = require("../user/user.module");
|
||||
const passport_1 = require("@nestjs/passport");
|
||||
const jwt_1 = require("@nestjs/jwt");
|
||||
const jwt_strategy_1 = require("../../common/auth/jwt.strategy");
|
||||
const jwtAuth_guard_1 = require("../../common/auth/jwtAuth.guard");
|
||||
const userBalance_service_1 = require("../userBalance/userBalance.service");
|
||||
const balance_entity_1 = require("../userBalance/balance.entity");
|
||||
const accountLog_entity_1 = require("../userBalance/accountLog.entity");
|
||||
const config_entity_1 = require("../globalConfig/config.entity");
|
||||
const common_1 = require("@nestjs/common");
|
||||
const jwt_1 = require("@nestjs/jwt");
|
||||
const passport_1 = require("@nestjs/passport");
|
||||
const typeorm_1 = require("@nestjs/typeorm");
|
||||
const nestjs_config_1 = require("nestjs-config");
|
||||
const whiteList_entity_1 = require("../chat/whiteList.entity");
|
||||
const chatGroup_entity_1 = require("../chatGroup/chatGroup.entity");
|
||||
const chatLog_entity_1 = require("../chatLog/chatLog.entity");
|
||||
const cramiPackage_entity_1 = require("../crami/cramiPackage.entity");
|
||||
const redisCache_service_1 = require("../redisCache/redisCache.service");
|
||||
const config_entity_1 = require("../globalConfig/config.entity");
|
||||
const mailer_service_1 = require("../mailer/mailer.service");
|
||||
const midjourney_entity_1 = require("../midjourney/midjourney.entity");
|
||||
const redisCache_module_1 = require("../redisCache/redisCache.module");
|
||||
const userBalance_entity_1 = require("../userBalance/userBalance.entity");
|
||||
const redisCache_service_1 = require("../redisCache/redisCache.service");
|
||||
const salesUsers_entity_1 = require("../sales/salesUsers.entity");
|
||||
const user_entity_1 = require("../user/user.entity");
|
||||
const whiteList_entity_1 = require("../chat/whiteList.entity");
|
||||
const user_module_1 = require("../user/user.module");
|
||||
const accountLog_entity_1 = require("../userBalance/accountLog.entity");
|
||||
const balance_entity_1 = require("../userBalance/balance.entity");
|
||||
const fingerprint_entity_1 = require("../userBalance/fingerprint.entity");
|
||||
const chatLog_entity_1 = require("../chatLog/chatLog.entity");
|
||||
const chatGroup_entity_1 = require("../chatGroup/chatGroup.entity");
|
||||
const midjourney_entity_1 = require("../midjourney/midjourney.entity");
|
||||
const userBalance_entity_1 = require("../userBalance/userBalance.entity");
|
||||
const userBalance_service_1 = require("../userBalance/userBalance.service");
|
||||
const verification_service_1 = require("./../verification/verification.service");
|
||||
const verifycation_entity_1 = require("./../verification/verifycation.entity");
|
||||
const auth_controller_1 = require("./auth.controller");
|
||||
const auth_service_1 = require("./auth.service");
|
||||
let AuthModule = class AuthModule {
|
||||
};
|
||||
AuthModule = __decorate([
|
||||
|
||||
220
dist/modules/auth/auth.service.js
vendored
220
dist/modules/auth/auth.service.js
vendored
@@ -13,23 +13,22 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.AuthService = void 0;
|
||||
const user_constant_1 = require("../../common/constants/user.constant");
|
||||
const utils_1 = require("../../common/utils");
|
||||
const globalConfig_service_1 = require("../globalConfig/globalConfig.service");
|
||||
const verification_constant_1 = require("../../common/constants/verification.constant");
|
||||
const verification_service_1 = require("./../verification/verification.service");
|
||||
const common_1 = require("@nestjs/common");
|
||||
const jwt_1 = require("@nestjs/jwt");
|
||||
const user_service_1 = require("../user/user.service");
|
||||
const mailer_service_1 = require("../mailer/mailer.service");
|
||||
const user_constant_1 = require("../../common/constants/user.constant");
|
||||
const userBalance_service_1 = require("../userBalance/userBalance.service");
|
||||
const config_entity_1 = require("../globalConfig/config.entity");
|
||||
const typeorm_1 = require("typeorm");
|
||||
const typeorm_2 = require("@nestjs/typeorm");
|
||||
const utils_1 = require("../../common/utils");
|
||||
const os = require("os");
|
||||
const redisCache_service_1 = require("../redisCache/redisCache.service");
|
||||
const svgCaptcha = require("svg-captcha");
|
||||
const typeorm_1 = require("@nestjs/typeorm");
|
||||
const bcrypt = require("bcryptjs");
|
||||
const os = require("os");
|
||||
const svgCaptcha = require("svg-captcha");
|
||||
const typeorm_2 = require("typeorm");
|
||||
const config_entity_1 = require("../globalConfig/config.entity");
|
||||
const mailer_service_1 = require("../mailer/mailer.service");
|
||||
const redisCache_service_1 = require("../redisCache/redisCache.service");
|
||||
const user_service_1 = require("../user/user.service");
|
||||
const userBalance_service_1 = require("../userBalance/userBalance.service");
|
||||
const verification_service_1 = require("./../verification/verification.service");
|
||||
let AuthService = class AuthService {
|
||||
constructor(configEntity, userService, jwtService, mailerService, verificationService, userBalanceService, redisCacheService, globalConfigService) {
|
||||
this.configEntity = configEntity;
|
||||
@@ -45,56 +44,75 @@ let AuthService = class AuthService {
|
||||
this.getIp();
|
||||
}
|
||||
async register(body, req) {
|
||||
await this.verificationService.verifyCaptcha(body);
|
||||
const user = await this.userService.createUserAndVerifycation(body, req);
|
||||
const { username, email, client, id } = user;
|
||||
const res = { username, email, id };
|
||||
client && (res.client = client);
|
||||
return res;
|
||||
}
|
||||
async registerByPhone(body, req) {
|
||||
const { username, password, phone, phoneCode, invitedBy } = body;
|
||||
await this.userService.verifyUserRegisterByPhone(body);
|
||||
const { username, password, contact, code, invitedBy } = body;
|
||||
let email = '', phone = '';
|
||||
const isEmail = /\S+@\S+\.\S+/.test(contact);
|
||||
const isPhone = /^\d{10,}$/.test(contact);
|
||||
if (isEmail) {
|
||||
email = contact;
|
||||
await this.userService.verifyUserRegister({ username, email });
|
||||
}
|
||||
else if (isPhone) {
|
||||
phone = contact;
|
||||
await this.userService.verifyUserRegister({ username, phone });
|
||||
}
|
||||
else {
|
||||
throw new common_1.HttpException('请提供有效的邮箱地址或手机号码。', common_1.HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
const nameSpace = await this.globalConfigService.getNamespace();
|
||||
const key = `${nameSpace}:PHONECODE:${phone}`;
|
||||
const redisPhoneCode = await this.redisCacheService.get({ key });
|
||||
if (!redisPhoneCode) {
|
||||
throw new common_1.HttpException('验证码已过期、请重新发送!', common_1.HttpStatus.BAD_REQUEST);
|
||||
const key = `${nameSpace}:CODE:${contact}`;
|
||||
const redisCode = await this.redisCacheService.get({ key });
|
||||
if (!redisCode) {
|
||||
common_1.Logger.log(`验证码过期: ${contact}`);
|
||||
throw new common_1.HttpException('验证码已过期,请重新发送!', common_1.HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
if (phoneCode !== redisPhoneCode) {
|
||||
throw new common_1.HttpException('验证码填写错误、请重新输入!', common_1.HttpStatus.BAD_REQUEST);
|
||||
if (code !== redisCode) {
|
||||
common_1.Logger.log(`验证码错误: ${contact} 输入的验证码: ${code}, 期望的验证码: ${redisCode}`);
|
||||
throw new common_1.HttpException('验证码填写错误,请重新输入!', common_1.HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
const email = `${(0, utils_1.createRandomUid)()}@nine.com`;
|
||||
const newUser = { username, password, phone, invitedBy, email, status: user_constant_1.UserStatusEnum.ACTIVE };
|
||||
console.log('开始创建用户...');
|
||||
let newUser;
|
||||
if (isEmail) {
|
||||
newUser = { username, password, email: contact, invitedBy, status: user_constant_1.UserStatusEnum.ACTIVE };
|
||||
}
|
||||
else {
|
||||
const email = `${(0, utils_1.createRandomUid)()}@aiweb.com`;
|
||||
newUser = { username, password, email, phone: contact, invitedBy, status: user_constant_1.UserStatusEnum.ACTIVE };
|
||||
}
|
||||
;
|
||||
console.log('获取默认用户头像...');
|
||||
const userDefautlAvatar = await this.globalConfigService.getConfigs(['userDefautlAvatar']);
|
||||
console.log(`使用默认用户头像: ${userDefautlAvatar}`);
|
||||
newUser.avatar = userDefautlAvatar;
|
||||
console.log('加密用户密码...');
|
||||
const hashedPassword = bcrypt.hashSync(password, 10);
|
||||
newUser.password = hashedPassword;
|
||||
console.log('保存新用户到数据库...');
|
||||
const u = await this.userService.createUser(newUser);
|
||||
console.log(`用户创建成功,用户ID: ${u.id}`);
|
||||
let inviteUser;
|
||||
if (invitedBy) {
|
||||
inviteUser = await this.userService.qureyUserInfoByInviteCode(invitedBy);
|
||||
}
|
||||
await this.userBalanceService.addBalanceToNewUser(u.id, inviteUser === null || inviteUser === void 0 ? void 0 : inviteUser.id);
|
||||
return;
|
||||
return { success: true, message: '注册成功' };
|
||||
}
|
||||
async login(user, req) {
|
||||
console.log(`开始用户登录流程,用户名: ${user.username}`);
|
||||
const u = await this.userService.verifyUserCredentials(user);
|
||||
const { username, id, email, role, openId, client } = u;
|
||||
if (!u) {
|
||||
console.error(`登录失败: 用户凭证无效 - 用户名: ${user.username}`);
|
||||
throw new common_1.HttpException('登录失败,用户凭证无效。', common_1.HttpStatus.UNAUTHORIZED);
|
||||
}
|
||||
const { username, id, email, role, openId, client, phone } = u;
|
||||
console.log(`用户凭证验证成功,用户ID: ${id}, 用户名: ${username}`);
|
||||
const ip = (0, utils_1.getClientIp)(req);
|
||||
await this.userService.savaLoginIp(id, ip);
|
||||
const token = await this.jwtService.sign({ username, id, email, role, openId, client });
|
||||
await this.redisCacheService.saveToken(id, token);
|
||||
return token;
|
||||
}
|
||||
async loginByPhone(body, req) {
|
||||
const u = await this.userService.verifyUserCredentials(body);
|
||||
const { username, id, email, role, openId, client } = u;
|
||||
const ip = (0, utils_1.getClientIp)(req);
|
||||
await this.userService.savaLoginIp(id, ip);
|
||||
const { phone } = body;
|
||||
console.log(`保存登录IP: ${ip} - 用户ID: ${id}`);
|
||||
const token = await this.jwtService.sign({ username, id, email, role, openId, client, phone });
|
||||
console.log(`JWT令牌生成成功 - 用户ID: ${id}`);
|
||||
await this.redisCacheService.saveToken(id, token);
|
||||
console.log(`令牌已保存到Redis - 用户ID: ${id}`);
|
||||
return token;
|
||||
}
|
||||
async loginByOpenId(user, req) {
|
||||
@@ -113,48 +131,6 @@ let AuthService = class AuthService {
|
||||
const { id } = req.user;
|
||||
return await this.userService.getUserInfo(id);
|
||||
}
|
||||
async activateAccount(params, res) {
|
||||
const emailConfigs = await this.configEntity.find({
|
||||
where: {
|
||||
configKey: (0, typeorm_1.In)([
|
||||
'registerSuccessEmailTitle',
|
||||
'registerSuccessEmailTeamName',
|
||||
'registerSuccessEmaileAppend',
|
||||
'registerFailEmailTitle',
|
||||
'registerFailEmailTeamName',
|
||||
]),
|
||||
},
|
||||
});
|
||||
const configMap = emailConfigs.reduce((pre, cur) => {
|
||||
pre[cur.configKey] = cur.configVal;
|
||||
return pre;
|
||||
}, {});
|
||||
try {
|
||||
const v = await this.verificationService.verifyCode(params, verification_constant_1.VerificationEnum.Registration);
|
||||
const { type, userId } = v;
|
||||
if (type !== verification_constant_1.VerificationEnum.Registration) {
|
||||
throw new common_1.HttpException('验证码类型错误', common_1.HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
const status = await this.userService.getUserStatus(userId);
|
||||
if (status === user_constant_1.UserStatusEnum.ACTIVE) {
|
||||
throw new common_1.HttpException('账户已被激活过', common_1.HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
await this.userService.updateUserStatus(v.userId, user_constant_1.UserStatusEnum.ACTIVE);
|
||||
const u = await this.userService.queryUserInfoById(v.userId);
|
||||
const { username, email, id, invitedBy } = u;
|
||||
let inviteUser;
|
||||
if (invitedBy) {
|
||||
inviteUser = await this.userService.qureyUserInfoByInviteCode(invitedBy);
|
||||
}
|
||||
await this.userBalanceService.addBalanceToNewUser(id, inviteUser === null || inviteUser === void 0 ? void 0 : inviteUser.id);
|
||||
res.redirect(`/api/auth/registerSuccess?id=${id.toString().padStart(4, '0')}&username=${username}&email=${email}®isterSuccessEmailTitle=${configMap.registerSuccessEmailTitle}®isterSuccessEmailTeamName=${configMap.registerSuccessEmailTeamName}®isterSuccessEmaileAppend=${configMap.registerSuccessEmaileAppend}`);
|
||||
}
|
||||
catch (error) {
|
||||
console.log('error: ', error);
|
||||
const message = error.response;
|
||||
res.redirect(`/api/auth/registerError?message=${message}®isterFailEmailTitle=${configMap.registerFailEmailTitle}®isterFailEmailTeamName=${configMap.registerFailEmailTeamName}`);
|
||||
}
|
||||
}
|
||||
async updatePassword(req, body) {
|
||||
const { id, client, role } = req.user;
|
||||
if (client && Number(client) > 0) {
|
||||
@@ -196,7 +172,7 @@ let AuthService = class AuthService {
|
||||
async captcha(parmas) {
|
||||
const nameSpace = await this.globalConfigService.getNamespace();
|
||||
const { color = '#fff' } = parmas;
|
||||
const captcha = svgCaptcha.createMathExpr({ background: color, height: 34, width: 120, noise: 3 });
|
||||
const captcha = svgCaptcha.createMathExpr({ background: color, height: 30, width: 120, noise: 5 });
|
||||
const text = captcha.text;
|
||||
const randomId = (0, utils_1.createRandomUid)();
|
||||
const key = `${nameSpace}:CAPTCHA:${randomId}`;
|
||||
@@ -206,20 +182,64 @@ let AuthService = class AuthService {
|
||||
code: randomId,
|
||||
};
|
||||
}
|
||||
async sendPhoneCode(body) {
|
||||
async sendCode(body) {
|
||||
await this.verificationService.verifyCaptcha(body);
|
||||
const { phone } = body;
|
||||
const nameSpace = await this.globalConfigService.getNamespace();
|
||||
const key = `${nameSpace}:PHONECODE:${phone}`;
|
||||
const ttl = await this.redisCacheService.ttl(key);
|
||||
if (ttl && ttl > 0) {
|
||||
throw new common_1.HttpException(`${ttl}秒内不得重复发送短信!`, common_1.HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
const { contact, username } = body;
|
||||
let email = '', phone = '';
|
||||
const code = (0, utils_1.createRandomCode)();
|
||||
const messageInfo = { phone, code };
|
||||
await this.verificationService.sendPhoneCode(messageInfo);
|
||||
await this.redisCacheService.set({ key, val: code }, 1 * 60);
|
||||
return '验证码发送成功、请填写验证码完成注册!';
|
||||
const isEmail = /\S+@\S+\.\S+/.test(contact);
|
||||
const isPhone = /^\d{10,}$/.test(contact);
|
||||
if (isEmail) {
|
||||
email = contact;
|
||||
await this.userService.verifyUserRegister({ username, email });
|
||||
}
|
||||
else if (isPhone) {
|
||||
phone = contact;
|
||||
await this.userService.verifyUserRegister({ username, phone });
|
||||
}
|
||||
else {
|
||||
throw new common_1.HttpException('请提供有效的邮箱地址或手机号码。', common_1.HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
const nameSpace = await this.globalConfigService.getNamespace();
|
||||
const key = `${nameSpace}:CODE:${contact}`;
|
||||
const ttl = await this.redisCacheService.ttl(key);
|
||||
if (ttl && ttl > 0 && isPhone) {
|
||||
throw new common_1.HttpException(`${ttl}秒内不得重复发送验证码!`, common_1.HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
if (isEmail) {
|
||||
const existingCode = await this.redisCacheService.get({ key });
|
||||
if (existingCode) {
|
||||
await this.mailerService.sendMail({
|
||||
to: email,
|
||||
context: {
|
||||
code: existingCode,
|
||||
},
|
||||
});
|
||||
return `验证码发送成功、请填写验证码完成注册!`;
|
||||
}
|
||||
else {
|
||||
try {
|
||||
await this.mailerService.sendMail({
|
||||
to: email,
|
||||
context: {
|
||||
code: code,
|
||||
},
|
||||
});
|
||||
console.log('邮件发送成功');
|
||||
}
|
||||
catch (error) {
|
||||
console.error('邮件发送失败', error);
|
||||
}
|
||||
await this.redisCacheService.set({ key, val: code }, 10 * 60);
|
||||
return `验证码发送成功、请填写验证码完成注册!`;
|
||||
}
|
||||
}
|
||||
else if (isPhone) {
|
||||
const messageInfo = { phone, code };
|
||||
await this.verificationService.sendPhoneCode(messageInfo);
|
||||
await this.redisCacheService.set({ key, val: code }, 10 * 60);
|
||||
return `验证码发送成功、请填写验证码完成注册!`;
|
||||
}
|
||||
}
|
||||
createTokenFromFingerprint(fingerprint) {
|
||||
const token = this.jwtService.sign({
|
||||
@@ -235,8 +255,8 @@ let AuthService = class AuthService {
|
||||
};
|
||||
AuthService = __decorate([
|
||||
(0, common_1.Injectable)(),
|
||||
__param(0, (0, typeorm_2.InjectRepository)(config_entity_1.ConfigEntity)),
|
||||
__metadata("design:paramtypes", [typeorm_1.Repository,
|
||||
__param(0, (0, typeorm_1.InjectRepository)(config_entity_1.ConfigEntity)),
|
||||
__metadata("design:paramtypes", [typeorm_2.Repository,
|
||||
user_service_1.UserService,
|
||||
jwt_1.JwtService,
|
||||
mailer_service_1.MailerService,
|
||||
|
||||
153
dist/modules/chat/apiDataService.service.js
vendored
Normal file
153
dist/modules/chat/apiDataService.service.js
vendored
Normal file
@@ -0,0 +1,153 @@
|
||||
"use strict";
|
||||
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
||||
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
||||
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
||||
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
||||
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
||||
};
|
||||
var __metadata = (this && this.__metadata) || function (k, v) {
|
||||
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
||||
};
|
||||
var ApiDataService_1;
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ApiDataService = void 0;
|
||||
const common_1 = require("@nestjs/common");
|
||||
const axios_1 = require("axios");
|
||||
const uuid = require("uuid");
|
||||
const globalConfig_service_1 = require("../globalConfig/globalConfig.service");
|
||||
const upload_service_1 = require("../upload/upload.service");
|
||||
let ApiDataService = ApiDataService_1 = class ApiDataService {
|
||||
constructor(uploadService, globalConfigService) {
|
||||
this.uploadService = uploadService;
|
||||
this.globalConfigService = globalConfigService;
|
||||
this.logger = new common_1.Logger(ApiDataService_1.name);
|
||||
}
|
||||
async chatFree(prompt, systemMessage, messagesHistory) {
|
||||
const { openaiBaseUrl = '', openaiBaseKey = '', openaiBaseModel, } = await this.globalConfigService.getConfigs([
|
||||
'openaiBaseKey',
|
||||
'openaiBaseUrl',
|
||||
'openaiBaseModel',
|
||||
]);
|
||||
const key = openaiBaseKey;
|
||||
const proxyUrl = openaiBaseUrl;
|
||||
let requestData = [];
|
||||
if (systemMessage) {
|
||||
requestData.push({
|
||||
"role": "system",
|
||||
"content": systemMessage
|
||||
});
|
||||
}
|
||||
if (messagesHistory && messagesHistory.length > 0) {
|
||||
requestData = requestData.concat(messagesHistory);
|
||||
}
|
||||
else {
|
||||
requestData.push({
|
||||
"role": "user",
|
||||
"content": prompt
|
||||
});
|
||||
}
|
||||
const options = {
|
||||
method: 'POST',
|
||||
url: `${proxyUrl}/v1/chat/completions`,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": `Bearer ${key}`,
|
||||
},
|
||||
data: {
|
||||
model: openaiBaseModel || 'gpt-3.5-turbo-0125',
|
||||
messages: requestData,
|
||||
},
|
||||
};
|
||||
try {
|
||||
const response = await (0, axios_1.default)(options);
|
||||
common_1.Logger.log(`全局模型调用成功, 返回结果: ${response === null || response === void 0 ? void 0 : response.data.choices[0].message.content}`);
|
||||
return response === null || response === void 0 ? void 0 : response.data.choices[0].message.content;
|
||||
}
|
||||
catch (error) {
|
||||
console.log('error: ', error);
|
||||
}
|
||||
}
|
||||
async dalleDraw(inputs, messagesHistory) {
|
||||
var _a, _b, _c, _d;
|
||||
common_1.Logger.log('开始提交 Dalle 绘图任务 ', 'DrawService');
|
||||
const { apiKey, model, proxyUrl, prompt, extraParam, timeout, onSuccess, onFailure } = inputs;
|
||||
const size = (extraParam === null || extraParam === void 0 ? void 0 : extraParam.size) || '1024x1024';
|
||||
let result = { answer: '', fileInfo: '', status: 2 };
|
||||
try {
|
||||
const options = {
|
||||
method: 'POST',
|
||||
url: `${proxyUrl}/v1/images/generations`,
|
||||
timeout: timeout,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${apiKey}`,
|
||||
},
|
||||
data: {
|
||||
model: model,
|
||||
prompt: prompt,
|
||||
size,
|
||||
},
|
||||
};
|
||||
const response = await (0, axios_1.default)(options);
|
||||
common_1.Logger.debug(`请求成功${JSON.stringify(response.data.data[0])}`);
|
||||
common_1.Logger.debug(`请求状态${JSON.stringify(response.status)}`);
|
||||
const url = response.data.data[0].url;
|
||||
try {
|
||||
const filename = `${Date.now()}-${uuid.v4().slice(0, 4)}.png`;
|
||||
common_1.Logger.debug(`------> 开始上传图片!!!`, 'DrawService');
|
||||
result.fileInfo = await this.uploadService.uploadFileFromUrl({ filename, url: url });
|
||||
common_1.Logger.debug(`图片上传成功,URL: ${result.fileInfo}`, 'DrawService');
|
||||
}
|
||||
catch (error) {
|
||||
common_1.Logger.error(`上传图片过程中出现错误: ${error}`, 'DrawService');
|
||||
}
|
||||
let revised_prompt_cn;
|
||||
try {
|
||||
revised_prompt_cn = await this.chatFree(`根据提示词{${response.data.data[0].revised_prompt}}, 模拟AI绘画机器人的语气,用中文回复,告诉用户已经画好了`);
|
||||
}
|
||||
catch (error) {
|
||||
revised_prompt_cn = `${prompt} 绘制成功`;
|
||||
common_1.Logger.error("翻译失败: ", error);
|
||||
}
|
||||
result.answer = revised_prompt_cn;
|
||||
result.status = 3;
|
||||
onSuccess(result);
|
||||
return;
|
||||
}
|
||||
catch (error) {
|
||||
result.status = 5;
|
||||
onFailure(result);
|
||||
const status = ((_a = error === null || error === void 0 ? void 0 : error.response) === null || _a === void 0 ? void 0 : _a.status) || 500;
|
||||
console.log('draw error: ', JSON.stringify(error), status);
|
||||
const message = (_d = (_c = (_b = error === null || error === void 0 ? void 0 : error.response) === null || _b === void 0 ? void 0 : _b.data) === null || _c === void 0 ? void 0 : _c.error) === null || _d === void 0 ? void 0 : _d.message;
|
||||
if (status === 429) {
|
||||
result.text = '当前请求已过载、请稍等会儿再试试吧!';
|
||||
return result;
|
||||
}
|
||||
if (status === 400 && message.includes('This request has been blocked by our content filters')) {
|
||||
result.text = '您的请求已被系统拒绝。您的提示可能存在一些非法的文本。';
|
||||
return result;
|
||||
}
|
||||
if (status === 400 && message.includes('Billing hard limit has been reached')) {
|
||||
result.text = '当前模型key已被封禁、已冻结当前调用Key、尝试重新对话试试吧!';
|
||||
return result;
|
||||
}
|
||||
if (status === 500) {
|
||||
result.text = '绘制图片失败,请检查你的提示词是否有非法描述!';
|
||||
return result;
|
||||
}
|
||||
if (status === 401) {
|
||||
result.text = '绘制图片失败,此次绘画被拒绝了!';
|
||||
return result;
|
||||
}
|
||||
result.text = '绘制图片失败,请稍后试试吧!';
|
||||
return result;
|
||||
}
|
||||
}
|
||||
};
|
||||
ApiDataService = ApiDataService_1 = __decorate([
|
||||
(0, common_1.Injectable)(),
|
||||
__metadata("design:paramtypes", [upload_service_1.UploadService,
|
||||
globalConfig_service_1.GlobalConfigService])
|
||||
], ApiDataService);
|
||||
exports.ApiDataService = ApiDataService;
|
||||
31
dist/modules/chat/chat.controller.js
vendored
31
dist/modules/chat/chat.controller.js
vendored
@@ -13,12 +13,11 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ChatController = void 0;
|
||||
const jwtAuth_guard_1 = require("../../common/auth/jwtAuth.guard");
|
||||
const swagger_1 = require("@nestjs/swagger");
|
||||
const jwtAuth_guard_1 = require("../../common/auth/jwtAuth.guard");
|
||||
const chat_service_1 = require("./chat.service");
|
||||
const common_1 = require("@nestjs/common");
|
||||
const chatProcess_dto_1 = require("./dto/chatProcess.dto");
|
||||
const chatDraw_dto_1 = require("./dto/chatDraw.dto");
|
||||
const adminAuth_guard_1 = require("../../common/auth/adminAuth.guard");
|
||||
const superAuth_guard_1 = require("../../common/auth/superAuth.guard");
|
||||
const globalConfig_service_1 = require("../globalConfig/globalConfig.service");
|
||||
@@ -37,23 +36,10 @@ let ChatController = class ChatController {
|
||||
return this.chatService.ttsProcess(body, req, res);
|
||||
}
|
||||
async mjFanyi(body, req) {
|
||||
const mjTranslatePrompt = await this.globalConfigService.getConfigs(['mjTranslatePrompt']);
|
||||
body.model = 'translation-';
|
||||
body.systemMessage =
|
||||
mjTranslatePrompt ||
|
||||
`接下来我会给你一些内容、我希望你帮我翻译成英文、不管我给你任何语言、你都回复我英文、如果给你了英文、依然回复我更加优化的英文、并且期望你不需要做任何多余的解释、给我英文即可、不要加任何东西、我只需要英文!`;
|
||||
return this.chatService.chatProcess(Object.assign(Object.assign({}, body), { specialModel: true }), req);
|
||||
return this.chatService.chatProcess(Object.assign(Object.assign({}, body), { specialModel: 'PromptOptimization' }), req);
|
||||
}
|
||||
async chatmind(body, req, res) {
|
||||
const mindCustomPrompt = await this.globalConfigService.getConfigs(['mindCustomPrompt']);
|
||||
body.model = 'mindmap-';
|
||||
body.systemMessage =
|
||||
mindCustomPrompt ||
|
||||
`我希望你使用markdown格式回答我得问题、我的需求是得到一份markdown格式的大纲、尽量做的精细、层级多一点、不管我问你什么、都需要您回复我一个大纲出来、我想使用大纲做思维导图、除了大纲之外、不要无关内容和总结。`;
|
||||
return this.chatService.chatProcess(Object.assign(Object.assign({}, body), { specialModel: true }), req, res);
|
||||
}
|
||||
async draw(body, req) {
|
||||
return await this.chatService.draw(body, req);
|
||||
return this.chatService.chatProcess(Object.assign(Object.assign({}, body), { specialModel: 'MindMap' }), req, res);
|
||||
}
|
||||
async setChatBoxType(req, body) {
|
||||
return await this.chatService.setChatBoxType(req, body);
|
||||
@@ -156,17 +142,6 @@ __decorate([
|
||||
__metadata("design:paramtypes", [chatProcess_dto_1.ChatProcessDto, Object, Object]),
|
||||
__metadata("design:returntype", Promise)
|
||||
], ChatController.prototype, "chatmind", null);
|
||||
__decorate([
|
||||
(0, common_1.Post)('chat-draw'),
|
||||
(0, swagger_1.ApiOperation)({ summary: 'gpt绘画' }),
|
||||
(0, common_1.UseGuards)(jwtAuth_guard_1.JwtAuthGuard),
|
||||
(0, swagger_1.ApiBearerAuth)(),
|
||||
__param(0, (0, common_1.Body)()),
|
||||
__param(1, (0, common_1.Req)()),
|
||||
__metadata("design:type", Function),
|
||||
__metadata("design:paramtypes", [chatDraw_dto_1.ChatDrawDto, Object]),
|
||||
__metadata("design:returntype", Promise)
|
||||
], ChatController.prototype, "draw", null);
|
||||
__decorate([
|
||||
(0, common_1.Post)('setChatBoxType'),
|
||||
(0, swagger_1.ApiOperation)({ summary: '添加修改分类类型' }),
|
||||
|
||||
46
dist/modules/chat/chat.module.js
vendored
46
dist/modules/chat/chat.module.js
vendored
@@ -8,32 +8,34 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ChatModule = void 0;
|
||||
const common_1 = require("@nestjs/common");
|
||||
const chat_controller_1 = require("./chat.controller");
|
||||
const chat_service_1 = require("./chat.service");
|
||||
const userBalance_service_1 = require("../userBalance/userBalance.service");
|
||||
const typeorm_1 = require("@nestjs/typeorm");
|
||||
const balance_entity_1 = require("../userBalance/balance.entity");
|
||||
const user_service_1 = require("../user/user.service");
|
||||
const app_entity_1 = require("../app/app.entity");
|
||||
const chatGroup_entity_1 = require("../chatGroup/chatGroup.entity");
|
||||
const chatLog_entity_1 = require("../chatLog/chatLog.entity");
|
||||
const chatLog_service_1 = require("../chatLog/chatLog.service");
|
||||
const cramiPackage_entity_1 = require("../crami/cramiPackage.entity");
|
||||
const config_entity_1 = require("../globalConfig/config.entity");
|
||||
const mailer_service_1 = require("../mailer/mailer.service");
|
||||
const midjourney_entity_1 = require("../midjourney/midjourney.entity");
|
||||
const redisCache_service_1 = require("../redisCache/redisCache.service");
|
||||
const salesUsers_entity_1 = require("../sales/salesUsers.entity");
|
||||
const user_entity_1 = require("../user/user.entity");
|
||||
const user_service_1 = require("../user/user.service");
|
||||
const accountLog_entity_1 = require("../userBalance/accountLog.entity");
|
||||
const balance_entity_1 = require("../userBalance/balance.entity");
|
||||
const fingerprint_entity_1 = require("../userBalance/fingerprint.entity");
|
||||
const userBalance_entity_1 = require("../userBalance/userBalance.entity");
|
||||
const userBalance_service_1 = require("../userBalance/userBalance.service");
|
||||
const verification_service_1 = require("../verification/verification.service");
|
||||
const verifycation_entity_1 = require("../verification/verifycation.entity");
|
||||
const chatLog_service_1 = require("../chatLog/chatLog.service");
|
||||
const chatLog_entity_1 = require("../chatLog/chatLog.entity");
|
||||
const accountLog_entity_1 = require("../userBalance/accountLog.entity");
|
||||
const config_entity_1 = require("../globalConfig/config.entity");
|
||||
const whiteList_entity_1 = require("./whiteList.entity");
|
||||
const cramiPackage_entity_1 = require("../crami/cramiPackage.entity");
|
||||
const chatGroup_entity_1 = require("../chatGroup/chatGroup.entity");
|
||||
const app_entity_1 = require("../app/app.entity");
|
||||
const userBalance_entity_1 = require("../userBalance/userBalance.entity");
|
||||
const salesUsers_entity_1 = require("../sales/salesUsers.entity");
|
||||
const redisCache_service_1 = require("../redisCache/redisCache.service");
|
||||
const fingerprint_entity_1 = require("../userBalance/fingerprint.entity");
|
||||
const midjourney_entity_1 = require("../midjourney/midjourney.entity");
|
||||
const chatBoxType_entity_1 = require("./chatBoxType.entity");
|
||||
const apiDataService_service_1 = require("./apiDataService.service");
|
||||
const chat_controller_1 = require("./chat.controller");
|
||||
const chat_service_1 = require("./chat.service");
|
||||
const chatBox_entity_1 = require("./chatBox.entity");
|
||||
const chatPreType_entity_1 = require("./chatPreType.entity");
|
||||
const chatBoxType_entity_1 = require("./chatBoxType.entity");
|
||||
const chatPre_entity_1 = require("./chatPre.entity");
|
||||
const chatPreType_entity_1 = require("./chatPreType.entity");
|
||||
const whiteList_entity_1 = require("./whiteList.entity");
|
||||
let ChatModule = class ChatModule {
|
||||
};
|
||||
ChatModule = __decorate([
|
||||
@@ -59,11 +61,11 @@ ChatModule = __decorate([
|
||||
chatBoxType_entity_1.ChatBoxTypeEntity,
|
||||
chatBox_entity_1.ChatBoxEntity,
|
||||
chatPreType_entity_1.ChatPreTypeEntity,
|
||||
chatPre_entity_1.ChatPreEntity
|
||||
chatPre_entity_1.ChatPreEntity,
|
||||
]),
|
||||
],
|
||||
controllers: [chat_controller_1.ChatController],
|
||||
providers: [chat_service_1.ChatService, userBalance_service_1.UserBalanceService, user_service_1.UserService, verification_service_1.VerificationService, chatLog_service_1.ChatLogService, redisCache_service_1.RedisCacheService],
|
||||
providers: [chat_service_1.ChatService, userBalance_service_1.UserBalanceService, user_service_1.UserService, verification_service_1.VerificationService, chatLog_service_1.ChatLogService, redisCache_service_1.RedisCacheService, apiDataService_service_1.ApiDataService, mailer_service_1.MailerService],
|
||||
exports: [chat_service_1.ChatService]
|
||||
})
|
||||
], ChatModule);
|
||||
|
||||
949
dist/modules/chat/chat.service.js
vendored
949
dist/modules/chat/chat.service.js
vendored
File diff suppressed because it is too large
Load Diff
36
dist/modules/chat/store.js
vendored
36
dist/modules/chat/store.js
vendored
@@ -1,8 +1,8 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.NineStore = void 0;
|
||||
const uuid_1 = require("uuid");
|
||||
const tiktoken_1 = require("@dqbd/tiktoken");
|
||||
const uuid_1 = require("uuid");
|
||||
const tokenizer = (0, tiktoken_1.get_encoding)('cl100k_base');
|
||||
class NineStore {
|
||||
constructor(options) {
|
||||
@@ -29,10 +29,14 @@ class NineStore {
|
||||
let { systemMessage = '', fileInfo, model, groupId, maxRounds = 5, maxModelTokens = 4000, isFileUpload = 0 } = options;
|
||||
let messages = [];
|
||||
if (systemMessage) {
|
||||
console.log('Adding system message:', systemMessage);
|
||||
messages.push({ role: 'system', content: systemMessage });
|
||||
}
|
||||
if (groupId) {
|
||||
console.log('Querying chat history for groupId:', groupId, 'with maxRounds:', maxRounds);
|
||||
const history = await chatLogService.chatHistory(groupId, maxRounds);
|
||||
console.log('Received history records:', history.length);
|
||||
let tempUserMessage = null;
|
||||
history.forEach((record) => {
|
||||
let content;
|
||||
if (isFileUpload === 2 && record.fileInfo) {
|
||||
@@ -47,7 +51,14 @@ class NineStore {
|
||||
else {
|
||||
content = record.text;
|
||||
}
|
||||
messages.push({ role: record.role, content });
|
||||
if (record.role === 'user') {
|
||||
tempUserMessage = { role: record.role, content };
|
||||
}
|
||||
else if (record.role === 'assistant' && tempUserMessage && content.trim() !== '') {
|
||||
messages.push(tempUserMessage);
|
||||
messages.push({ role: record.role, content });
|
||||
tempUserMessage = null;
|
||||
}
|
||||
});
|
||||
}
|
||||
let currentMessageContent;
|
||||
@@ -66,18 +77,29 @@ class NineStore {
|
||||
messages.push({ role: 'user', content: currentMessageContent });
|
||||
let totalTokens = await this._getTokenCount(messages);
|
||||
while (totalTokens > maxModelTokens / 2) {
|
||||
let foundNonSystemMessage = false;
|
||||
if (messages.length === 2 && messages[0].role === 'system' && messages[1].role === 'user') {
|
||||
break;
|
||||
}
|
||||
let foundPairToDelete = false;
|
||||
for (let i = 0; i < messages.length; i++) {
|
||||
if (messages[i].role !== 'system') {
|
||||
if (messages[i].role !== 'system' && messages[i + 1] && messages[i + 1].role === 'assistant') {
|
||||
messages.splice(i, 2);
|
||||
foundNonSystemMessage = true;
|
||||
foundPairToDelete = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!foundNonSystemMessage) {
|
||||
break;
|
||||
if (!foundPairToDelete) {
|
||||
for (let i = 0; i < messages.length; i++) {
|
||||
if (messages[i].role === 'user') {
|
||||
messages.splice(i, 1);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
totalTokens = await this._getTokenCount(messages);
|
||||
if (messages.length <= 2) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return {
|
||||
messagesHistory: messages,
|
||||
|
||||
43
dist/modules/chatGroup/chatGroup.service.js
vendored
43
dist/modules/chatGroup/chatGroup.service.js
vendored
@@ -14,11 +14,11 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ChatGroupService = void 0;
|
||||
const common_1 = require("@nestjs/common");
|
||||
const chatGroup_entity_1 = require("./chatGroup.entity");
|
||||
const typeorm_1 = require("@nestjs/typeorm");
|
||||
const typeorm_2 = require("typeorm");
|
||||
const app_entity_1 = require("../app/app.entity");
|
||||
const models_service_1 = require("../models/models.service");
|
||||
const chatGroup_entity_1 = require("./chatGroup.entity");
|
||||
let ChatGroupService = class ChatGroupService {
|
||||
constructor(chatGroupEntity, appEntity, modelsService) {
|
||||
this.chatGroupEntity = chatGroupEntity;
|
||||
@@ -28,32 +28,39 @@ let ChatGroupService = class ChatGroupService {
|
||||
async create(body, req) {
|
||||
const { id } = req.user;
|
||||
const { appId, modelConfig: bodyModelConfig } = body;
|
||||
let modelConfig = bodyModelConfig;
|
||||
let modelConfig = bodyModelConfig || await this.modelsService.getBaseConfig(appId);
|
||||
if (!modelConfig) {
|
||||
modelConfig = await this.modelsService.getBaseConfig(appId);
|
||||
if (!modelConfig) {
|
||||
throw new common_1.HttpException('管理员未配置任何AI模型、请先联系管理员开通聊天模型配置!', common_1.HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
throw new common_1.HttpException('管理员未配置任何AI模型、请先联系管理员开通聊天模型配置!', common_1.HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
const params = { title: '新对话', userId: id };
|
||||
modelConfig = JSON.parse(JSON.stringify(modelConfig));
|
||||
const params = { title: '新对话', userId: id, appId };
|
||||
if (appId) {
|
||||
const appInfo = await this.appEntity.findOne({ where: { id: appId } });
|
||||
if (!appInfo) {
|
||||
throw new common_1.HttpException('非法操作、您在使用一个不存在的应用!', common_1.HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
const { status, name } = appInfo;
|
||||
const existingGroupCount = await this.chatGroupEntity.count({ where: { userId: id, appId, isDelete: false } });
|
||||
if (existingGroupCount > 0) {
|
||||
throw new common_1.HttpException('当前应用已经开启了一个对话无需新建了!', common_1.HttpStatus.BAD_REQUEST);
|
||||
const { status, name, isFixedModel, isGPTs, appModel, coverImg } = appInfo;
|
||||
Object.assign(modelConfig.modelInfo, {
|
||||
isGPTs,
|
||||
isFixedModel,
|
||||
modelAvatar: coverImg,
|
||||
modelName: name
|
||||
});
|
||||
if (isGPTs === 1 || isFixedModel === 1) {
|
||||
const appModelKey = await this.modelsService.getCurrentModelKeyInfo(isFixedModel === 1 ? appModel : 'gpts');
|
||||
Object.assign(modelConfig.modelInfo, {
|
||||
deductType: appModelKey.deductType,
|
||||
deduct: appModelKey.deduct,
|
||||
model: appModel,
|
||||
isFileUpload: appModelKey.isFileUpload
|
||||
});
|
||||
}
|
||||
if (![1, 3, 4, 5].includes(status)) {
|
||||
throw new common_1.HttpException('非法操作、您在使用一个未启用的应用!', common_1.HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
if (name) {
|
||||
params['title'] = name;
|
||||
params.title = name;
|
||||
}
|
||||
params['appId'] = appId;
|
||||
modelConfig.appId = appId;
|
||||
}
|
||||
const newGroup = await this.chatGroupEntity.save(Object.assign(Object.assign({}, params), { config: JSON.stringify(modelConfig) }));
|
||||
return newGroup;
|
||||
@@ -62,7 +69,8 @@ let ChatGroupService = class ChatGroupService {
|
||||
try {
|
||||
const { id } = req.user;
|
||||
const params = { userId: id, isDelete: false };
|
||||
const res = await this.chatGroupEntity.find({ where: params, order: { isSticky: 'DESC', id: 'DESC' } });
|
||||
const res = await this.chatGroupEntity.find({ where: params, order: { isSticky: 'DESC', updatedAt: 'DESC' } });
|
||||
return res;
|
||||
const appIds = res.filter(t => t.appId).map(t => t.appId);
|
||||
const appInfos = await this.appEntity.find({ where: { id: (0, typeorm_2.In)(appIds) } });
|
||||
return res.map((item) => {
|
||||
@@ -105,6 +113,11 @@ let ChatGroupService = class ChatGroupService {
|
||||
throw new common_1.HttpException('更新对话失败!', common_1.HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
async updateTime(groupId) {
|
||||
await this.chatGroupEntity.update(groupId, {
|
||||
updatedAt: new Date()
|
||||
});
|
||||
}
|
||||
async del(body, req) {
|
||||
const { groupId } = body;
|
||||
const { id } = req.user;
|
||||
|
||||
6
dist/modules/chatLog/chatLog.entity.js
vendored
6
dist/modules/chatLog/chatLog.entity.js
vendored
@@ -10,8 +10,8 @@ var __metadata = (this && this.__metadata) || function (k, v) {
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ChatLogEntity = void 0;
|
||||
const typeorm_1 = require("typeorm");
|
||||
const baseEntity_1 = require("../../common/entity/baseEntity");
|
||||
const typeorm_1 = require("typeorm");
|
||||
let ChatLogEntity = class ChatLogEntity extends baseEntity_1.BaseEntity {
|
||||
};
|
||||
__decorate([
|
||||
@@ -42,6 +42,10 @@ __decorate([
|
||||
(0, typeorm_1.Column)({ comment: '附加参数', nullable: true }),
|
||||
__metadata("design:type", String)
|
||||
], ChatLogEntity.prototype, "extraParam", void 0);
|
||||
__decorate([
|
||||
(0, typeorm_1.Column)({ comment: '插件参数', nullable: true }),
|
||||
__metadata("design:type", String)
|
||||
], ChatLogEntity.prototype, "pluginParam", void 0);
|
||||
__decorate([
|
||||
(0, typeorm_1.Column)({ comment: '回答的答案', type: 'text', nullable: true }),
|
||||
__metadata("design:type", String)
|
||||
|
||||
84
dist/modules/chatLog/chatLog.service.js
vendored
84
dist/modules/chatLog/chatLog.service.js
vendored
@@ -13,20 +13,22 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ChatLogService = void 0;
|
||||
const balance_constant_1 = require("../../common/constants/balance.constant");
|
||||
const utils_1 = require("../../common/utils");
|
||||
const common_1 = require("@nestjs/common");
|
||||
const typeorm_1 = require("@nestjs/typeorm");
|
||||
const chatLog_entity_1 = require("./chatLog.entity");
|
||||
const typeorm_2 = require("typeorm");
|
||||
const balance_constant_1 = require("../../common/constants/balance.constant");
|
||||
const user_entity_1 = require("../user/user.entity");
|
||||
const utils_1 = require("../../common/utils");
|
||||
const exceljs_1 = require("exceljs");
|
||||
const typeorm_2 = require("typeorm");
|
||||
const chatGroup_entity_1 = require("../chatGroup/chatGroup.entity");
|
||||
const user_entity_1 = require("../user/user.entity");
|
||||
const chatLog_entity_1 = require("./chatLog.entity");
|
||||
const models_service_1 = require("../models/models.service");
|
||||
let ChatLogService = class ChatLogService {
|
||||
constructor(chatLogEntity, userEntity, chatGroupEntity) {
|
||||
constructor(chatLogEntity, userEntity, chatGroupEntity, modelsService) {
|
||||
this.chatLogEntity = chatLogEntity;
|
||||
this.userEntity = userEntity;
|
||||
this.chatGroupEntity = chatGroupEntity;
|
||||
this.modelsService = modelsService;
|
||||
}
|
||||
async saveChatLog(logInfo) {
|
||||
const savedLog = await this.chatLogEntity.save(logInfo);
|
||||
@@ -71,14 +73,11 @@ let ChatLogService = class ChatLogService {
|
||||
}
|
||||
async querAllDrawLog(params) {
|
||||
const { page = 1, size = 20, rec, userId, model } = params;
|
||||
const where = { type: balance_constant_1.ChatType.PAINT, prompt: (0, typeorm_2.Not)(''), answer: (0, typeorm_2.Not)('') };
|
||||
const where = { type: 2, prompt: (0, typeorm_2.Not)(''), answer: (0, typeorm_2.Not)(''), fileInfo: (0, typeorm_2.Not)(''), };
|
||||
rec && Object.assign(where, { rec });
|
||||
userId && Object.assign(where, { userId });
|
||||
if (model) {
|
||||
where.model = model;
|
||||
if (model === 'DALL-E2') {
|
||||
where.model = (0, typeorm_2.In)(['DALL-E2', 'dall-e-3']);
|
||||
}
|
||||
}
|
||||
const [rows, count] = await this.chatLogEntity.findAndCount({
|
||||
order: { id: 'DESC' },
|
||||
@@ -88,25 +87,23 @@ let ChatLogService = class ChatLogService {
|
||||
});
|
||||
rows.forEach((r) => {
|
||||
var _a;
|
||||
if (r.type === 'paintCount') {
|
||||
const w = r.model === 'mj' ? 310 : 160;
|
||||
const imgType = r.answer.includes('cos') ? 'tencent' : 'ali';
|
||||
const compress = imgType === 'tencent' ? `?imageView2/1/w/${w}/q/55` : `?x-oss-process=image/resize,w_${w}`;
|
||||
r.thumbImg = r.answer + compress;
|
||||
try {
|
||||
const detailInfo = r.extend ? JSON.parse(r.extend) : null;
|
||||
const w = r.model === 'midjourney' ? 310 : 160;
|
||||
const imgType = r.answer.includes('cos') ? 'tencent' : 'ali';
|
||||
const compress = imgType === 'tencent' ? `?imageView2/1/w/${w}/q/55` : `?x-oss-process=image/resize,w_${w}`;
|
||||
r.thumbImg = r.answer + compress;
|
||||
try {
|
||||
const detailInfo = r.extend ? JSON.parse(r.extend) : null;
|
||||
if (detailInfo) {
|
||||
if (detailInfo) {
|
||||
if (detailInfo) {
|
||||
r.isGroup = ((_a = detailInfo === null || detailInfo === void 0 ? void 0 : detailInfo.components[0]) === null || _a === void 0 ? void 0 : _a.components.length) === 5;
|
||||
}
|
||||
else {
|
||||
r.isGroup = false;
|
||||
}
|
||||
r.isGroup = ((_a = detailInfo === null || detailInfo === void 0 ? void 0 : detailInfo.components[0]) === null || _a === void 0 ? void 0 : _a.components.length) === 5;
|
||||
}
|
||||
else {
|
||||
r.isGroup = false;
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
console.log('querAllDrawLog Json parse error', error);
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
console.log('querAllDrawLog Json parse error', error);
|
||||
}
|
||||
});
|
||||
return { rows, count };
|
||||
@@ -207,7 +204,7 @@ let ChatLogService = class ChatLogService {
|
||||
}
|
||||
const list = await this.chatLogEntity.find({ where });
|
||||
return list.map((item) => {
|
||||
const { prompt, role, answer, createdAt, model, modelName, type, status, action, drawId, id, fileInfo, ttsUrl, customId } = item;
|
||||
const { prompt, role, answer, createdAt, model, modelName, type, status, action, drawId, id, fileInfo, ttsUrl, customId, pluginParam } = item;
|
||||
return {
|
||||
chatId: id,
|
||||
dateTime: (0, utils_1.formatDate)(createdAt),
|
||||
@@ -223,15 +220,19 @@ let ChatLogService = class ChatLogService {
|
||||
ttsUrl: ttsUrl,
|
||||
model: model,
|
||||
modelName: modelName,
|
||||
pluginParam: pluginParam,
|
||||
};
|
||||
});
|
||||
}
|
||||
async chatHistory(groupId, rounds) {
|
||||
if (rounds === 0) {
|
||||
return [];
|
||||
}
|
||||
const where = { isDelete: false, groupId: groupId };
|
||||
const list = await this.chatLogEntity.find({
|
||||
where,
|
||||
order: {
|
||||
createdAt: 'ASC'
|
||||
createdAt: 'DESC'
|
||||
},
|
||||
take: rounds * 2
|
||||
});
|
||||
@@ -242,7 +243,7 @@ let ChatLogService = class ChatLogService {
|
||||
text: role === 'user' ? prompt : answer,
|
||||
fileInfo: fileInfo,
|
||||
};
|
||||
});
|
||||
}).reverse();
|
||||
}
|
||||
async deleteChatLog(req, body) {
|
||||
const { id: userId } = req.user;
|
||||
@@ -285,6 +286,28 @@ let ChatLogService = class ChatLogService {
|
||||
});
|
||||
return { rows, count };
|
||||
}
|
||||
async checkModelLimits(userId, model) {
|
||||
const oneHourAgo = new Date(Date.now() - 3600 * 1000);
|
||||
let adjustedUsageCount;
|
||||
try {
|
||||
const usageCount = await this.chatLogEntity.count({
|
||||
where: {
|
||||
userId: userId.id,
|
||||
model,
|
||||
createdAt: (0, typeorm_2.MoreThan)(oneHourAgo),
|
||||
}
|
||||
});
|
||||
adjustedUsageCount = Math.ceil(usageCount / 2);
|
||||
common_1.Logger.debug(`用户ID: ${userId.id} 模型: ${model} 一小时内已调用: ${adjustedUsageCount} 次`);
|
||||
}
|
||||
catch (error) {
|
||||
common_1.Logger.error(`查询数据库出错 - 用户ID: ${userId}, 模型: ${model}, 错误信息: ${error.message}`);
|
||||
}
|
||||
const modelInfo = await this.modelsService.getCurrentModelKeyInfo(model);
|
||||
if (adjustedUsageCount > modelInfo.modelLimits) {
|
||||
throw new common_1.HttpException('1 小时内请求次数过多,请稍后再试!', common_1.HttpStatus.TOO_MANY_REQUESTS);
|
||||
}
|
||||
}
|
||||
};
|
||||
ChatLogService = __decorate([
|
||||
(0, common_1.Injectable)(),
|
||||
@@ -293,6 +316,7 @@ ChatLogService = __decorate([
|
||||
__param(2, (0, typeorm_1.InjectRepository)(chatGroup_entity_1.ChatGroupEntity)),
|
||||
__metadata("design:paramtypes", [typeorm_2.Repository,
|
||||
typeorm_2.Repository,
|
||||
typeorm_2.Repository])
|
||||
typeorm_2.Repository,
|
||||
models_service_1.ModelsService])
|
||||
], ChatLogService);
|
||||
exports.ChatLogService = ChatLogService;
|
||||
|
||||
42
dist/modules/database/database.service.js
vendored
42
dist/modules/database/database.service.js
vendored
@@ -11,8 +11,8 @@ var __metadata = (this && this.__metadata) || function (k, v) {
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.DatabaseService = void 0;
|
||||
const common_1 = require("@nestjs/common");
|
||||
const typeorm_1 = require("typeorm");
|
||||
const bcrypt = require("bcryptjs");
|
||||
const typeorm_1 = require("typeorm");
|
||||
let DatabaseService = class DatabaseService {
|
||||
constructor(connection) {
|
||||
this.connection = connection;
|
||||
@@ -20,6 +20,7 @@ let DatabaseService = class DatabaseService {
|
||||
async onModuleInit() {
|
||||
await this.checkSuperAdmin();
|
||||
await this.checkSiteBaseConfig();
|
||||
await this.createSystemReservedApps();
|
||||
}
|
||||
async checkSuperAdmin() {
|
||||
const user = await this.connection.query(`SELECT * FROM users WHERE role = 'super'`);
|
||||
@@ -91,25 +92,6 @@ let DatabaseService = class DatabaseService {
|
||||
{ configKey: 'openaiBaseKey', configVal: 'sk-', public: 0, encry: 0 },
|
||||
{ configKey: 'mjTranslatePrompt', configVal: `Translate any given phrase from any language into English. For instance, when I input '{可爱的熊猫}', you should output '{cute panda}', with no period at the end.`, public: 0, encry: 0 },
|
||||
{ configKey: 'noticeInfo', configVal: noticeInfo, public: 1, encry: 0 },
|
||||
{ configKey: 'registerVerifyEmailTitle', configVal: 'AIWeb账号验证', public: 0, encry: 0 },
|
||||
{
|
||||
configKey: 'registerVerifyEmailDesc',
|
||||
configVal: '欢迎使用AI Web团队的产品服务,请在五分钟内完成你的账号激活,点击以下按钮激活您的账号,',
|
||||
public: 0,
|
||||
encry: 0,
|
||||
},
|
||||
{ configKey: 'registerVerifyEmailFrom', configVal: 'AI Web团队', public: 0, encry: 0 },
|
||||
{ configKey: 'registerVerifyExpir', configVal: '1800', public: 0, encry: 0 },
|
||||
{ configKey: 'registerSuccessEmailTitle', configVal: 'AIWeb账号激活成功', public: 0, encry: 0 },
|
||||
{ configKey: 'registerSuccessEmailTeamName', configVal: 'AIWeb', public: 0, encry: 0 },
|
||||
{
|
||||
configKey: 'registerSuccessEmaileAppend',
|
||||
configVal: ',请妥善保管您的账号,祝您使用愉快',
|
||||
public: 0,
|
||||
encry: 0,
|
||||
},
|
||||
{ configKey: 'registerFailEmailTitle', configVal: 'AIWeb账号激活失败', public: 0, encry: 0 },
|
||||
{ configKey: 'registerFailEmailTeamName', configVal: 'AIWeb团队', public: 0, encry: 0 },
|
||||
{ configKey: 'registerSendStatus', configVal: '1', public: 1, encry: 0 },
|
||||
{ configKey: 'registerSendModel3Count', configVal: '30', public: 1, encry: 0 },
|
||||
{ configKey: 'registerSendModel4Count', configVal: '3', public: 1, encry: 0 },
|
||||
@@ -138,6 +120,26 @@ let DatabaseService = class DatabaseService {
|
||||
throw new common_1.HttpException('创建默认网站配置失败!', common_1.HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
}
|
||||
async createSystemReservedApps() {
|
||||
const systemApps = [
|
||||
{ name: "提示词优化PromptOptimization", catId: 9900, des: "PromptOptimization", preset: "Translate any given phrase from any language into English. For instance, when I input '{可爱的熊猫}', you should output '{cute panda}', with no period at the end.", appModel: "gpt-3.5-turbo", isFixedModel: 1, isSystemReserved: 1 },
|
||||
{ name: "思维导图MindMap", catId: 9900, des: "MindMap", preset: "我希望你使用markdown格式回答我得问题、我的需求是得到一份markdown格式的大纲、尽量做的精细、层级多一点、不管我问你什么、都需要您回复我一个大纲出来、我想使用大纲做思维导图、除了大纲之外、不要无关内容和总结。", appModel: "gpt-3.5-turbo", isFixedModel: 1, isSystemReserved: 1 },
|
||||
];
|
||||
try {
|
||||
for (const app of systemApps) {
|
||||
const result = await this.connection.query(`SELECT COUNT(*) AS count FROM app WHERE name = ? AND des = ? AND isSystemReserved = ?`, [app.name, app.des, app.isSystemReserved]);
|
||||
const count = parseInt(result[0].count, 10);
|
||||
if (count === 0) {
|
||||
await this.connection.query(`INSERT INTO app (name, catId, des, preset, appModel, isFixedModel, isSystemReserved) VALUES (?, ?, ?, ?, ?, ?, ?)`, [app.name, app.catId, app.des, app.preset, app.appModel, app.isFixedModel, app.isSystemReserved]);
|
||||
common_1.Logger.log(`系统预留应用${app.name}创建成功`, 'DatabaseService');
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
console.log('创建系统预留应用过程中出现错误: ', error);
|
||||
throw new Error('创建系统预留应用失败!');
|
||||
}
|
||||
}
|
||||
};
|
||||
DatabaseService = __decorate([
|
||||
(0, common_1.Injectable)(),
|
||||
|
||||
54
dist/modules/draw copy/draw.controller.js
vendored
54
dist/modules/draw copy/draw.controller.js
vendored
@@ -1,54 +0,0 @@
|
||||
"use strict";
|
||||
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
||||
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
||||
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
||||
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
||||
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
||||
};
|
||||
var __metadata = (this && this.__metadata) || function (k, v) {
|
||||
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
||||
};
|
||||
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
||||
return function (target, key) { decorator(target, key, paramIndex); }
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.DrawController = void 0;
|
||||
const draw_service_1 = require("./draw.service");
|
||||
const common_1 = require("@nestjs/common");
|
||||
const swagger_1 = require("@nestjs/swagger");
|
||||
const jwtAuth_guard_1 = require("../../common/auth/jwtAuth.guard");
|
||||
const chatDraw_dto_1 = require("./dto/chatDraw.dto");
|
||||
let DrawController = class DrawController {
|
||||
constructor(drawService) {
|
||||
this.drawService = drawService;
|
||||
}
|
||||
getEngines() {
|
||||
return this.drawService.getEngines();
|
||||
}
|
||||
textToImage(body) {
|
||||
return this.drawService.drawTextToImage(body);
|
||||
}
|
||||
};
|
||||
__decorate([
|
||||
(0, common_1.Get)('engines'),
|
||||
(0, swagger_1.ApiOperation)({ summary: '获取stable Diffusion 模型' }),
|
||||
__metadata("design:type", Function),
|
||||
__metadata("design:paramtypes", []),
|
||||
__metadata("design:returntype", void 0)
|
||||
], DrawController.prototype, "getEngines", null);
|
||||
__decorate([
|
||||
(0, common_1.Post)('drawTextToImage'),
|
||||
(0, swagger_1.ApiOperation)({ summary: 'stable Diffusion绘画' }),
|
||||
(0, common_1.UseGuards)(jwtAuth_guard_1.JwtAuthGuard),
|
||||
(0, swagger_1.ApiBearerAuth)(),
|
||||
__param(0, (0, common_1.Body)()),
|
||||
__metadata("design:type", Function),
|
||||
__metadata("design:paramtypes", [chatDraw_dto_1.StableDrawDto]),
|
||||
__metadata("design:returntype", void 0)
|
||||
], DrawController.prototype, "textToImage", null);
|
||||
DrawController = __decorate([
|
||||
(0, swagger_1.ApiTags)('draw'),
|
||||
(0, common_1.Controller)('draw'),
|
||||
__metadata("design:paramtypes", [draw_service_1.DrawService])
|
||||
], DrawController);
|
||||
exports.DrawController = DrawController;
|
||||
81
dist/modules/draw copy/draw.service.js
vendored
81
dist/modules/draw copy/draw.service.js
vendored
@@ -1,81 +0,0 @@
|
||||
"use strict";
|
||||
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
||||
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
||||
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
||||
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
||||
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
||||
};
|
||||
var __metadata = (this && this.__metadata) || function (k, v) {
|
||||
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.DrawService = void 0;
|
||||
const common_1 = require("@nestjs/common");
|
||||
const axios_1 = require("axios");
|
||||
const uuid = require("uuid");
|
||||
const upload_service_1 = require("../upload/upload.service");
|
||||
let DrawService = class DrawService {
|
||||
constructor(uploadService) {
|
||||
this.uploadService = uploadService;
|
||||
}
|
||||
async onModuleInit() {
|
||||
var _a;
|
||||
this.apiHost = (_a = process.env.API_HOST) !== null && _a !== void 0 ? _a : 'https://api.stability.ai';
|
||||
this.apiKey = process.env.STABILITY_API_KEY;
|
||||
if (!this.apiKey) {
|
||||
this.apiKey = '*********';
|
||||
}
|
||||
this.Authorization = `Bearer ${this.apiKey}`;
|
||||
}
|
||||
async getEngines() {
|
||||
var _a, _b;
|
||||
const url = `${this.apiHost}/v1/engines/list`;
|
||||
const res = await (0, axios_1.default)(url, {
|
||||
method: 'GET',
|
||||
headers: { Authorization: this.Authorization },
|
||||
});
|
||||
if (res.status === 401) {
|
||||
console.log(`stability api key is invalid, ${(_a = res === null || res === void 0 ? void 0 : res.data) === null || _a === void 0 ? void 0 : _a.message}`);
|
||||
}
|
||||
if (res.status !== 200) {
|
||||
console.log(`${res.status} ${(_b = res === null || res === void 0 ? void 0 : res.data) === null || _b === void 0 ? void 0 : _b.message}}`);
|
||||
throw new common_1.HttpException('获取列表失败', common_1.HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
return res.data;
|
||||
}
|
||||
async drawTextToImage(body) {
|
||||
const { engineId = 'stable-diffusion-768-v2-1' } = body;
|
||||
const headers = {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: 'application/json',
|
||||
Authorization: this.Authorization,
|
||||
};
|
||||
const url = `${this.apiHost}/v1/generation/${engineId}/text-to-image`;
|
||||
try {
|
||||
const response = await axios_1.default.post(url, body, { headers });
|
||||
if (response.status !== 200) {
|
||||
throw new common_1.HttpException('绘制失败', common_1.HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
const resImageBasetask = [];
|
||||
for (const item of response.data.artifacts) {
|
||||
const filename = uuid.v4().slice(0, 10) + '.png';
|
||||
const buffer = Buffer.from(item.base64, 'base64');
|
||||
resImageBasetask.push(this.uploadService.uploadFile({ filename, buffer }));
|
||||
}
|
||||
const urls = await Promise.all(resImageBasetask);
|
||||
return urls;
|
||||
}
|
||||
catch (error) {
|
||||
if (!(error === null || error === void 0 ? void 0 : error.response)) {
|
||||
throw new common_1.HttpException('绘制失败', common_1.HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
const { status, data } = error.response;
|
||||
throw new common_1.HttpException(data.message, status);
|
||||
}
|
||||
}
|
||||
};
|
||||
DrawService = __decorate([
|
||||
(0, common_1.Injectable)(),
|
||||
__metadata("design:paramtypes", [upload_service_1.UploadService])
|
||||
], DrawService);
|
||||
exports.DrawService = DrawService;
|
||||
112
dist/modules/draw copy/dto/chatDraw.dto.js
vendored
112
dist/modules/draw copy/dto/chatDraw.dto.js
vendored
@@ -1,112 +0,0 @@
|
||||
"use strict";
|
||||
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
||||
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
||||
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
||||
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
||||
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
||||
};
|
||||
var __metadata = (this && this.__metadata) || function (k, v) {
|
||||
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.StableDrawDto = exports.TextPromptDto = void 0;
|
||||
const class_validator_1 = require("class-validator");
|
||||
const swagger_1 = require("@nestjs/swagger");
|
||||
const class_transformer_1 = require("class-transformer");
|
||||
class TextPromptDto {
|
||||
}
|
||||
__decorate([
|
||||
(0, class_validator_1.IsString)(),
|
||||
__metadata("design:type", String)
|
||||
], TextPromptDto.prototype, "text", void 0);
|
||||
__decorate([
|
||||
(0, class_validator_1.IsNumber)(),
|
||||
__metadata("design:type", Number)
|
||||
], TextPromptDto.prototype, "weight", void 0);
|
||||
exports.TextPromptDto = TextPromptDto;
|
||||
class StableDrawDto {
|
||||
constructor() {
|
||||
this.samples = 1;
|
||||
this.width = 512;
|
||||
this.height = 512;
|
||||
this.cfg_scale = 7;
|
||||
this.steps = 30;
|
||||
this.clip_guidance_preset = 'NONE';
|
||||
}
|
||||
}
|
||||
__decorate([
|
||||
(0, swagger_1.ApiProperty)({ example: 'stable-diffusion-512-v2-1', default: 512, description: '模型id', required: true }),
|
||||
(0, class_validator_1.IsDefined)({ message: '模型id是必传参数' }),
|
||||
__metadata("design:type", String)
|
||||
], StableDrawDto.prototype, "engineId", void 0);
|
||||
__decorate([
|
||||
(0, swagger_1.ApiProperty)({
|
||||
example: [
|
||||
{
|
||||
text: 'Draw a cute little dog',
|
||||
weight: 0.5,
|
||||
},
|
||||
],
|
||||
description: '绘画描述信息',
|
||||
}),
|
||||
(0, class_transformer_1.Type)(() => TextPromptDto),
|
||||
(0, class_validator_1.ValidateNested)({ each: true }),
|
||||
__metadata("design:type", Array)
|
||||
], StableDrawDto.prototype, "text_prompts", void 0);
|
||||
__decorate([
|
||||
(0, swagger_1.ApiProperty)({ example: 1, description: '绘画张数', required: true }),
|
||||
__metadata("design:type", Object)
|
||||
], StableDrawDto.prototype, "samples", void 0);
|
||||
__decorate([
|
||||
(0, swagger_1.ApiProperty)({ example: 512, default: 512, description: '图片尺寸宽度' }),
|
||||
(0, class_validator_1.Max)(1024, { message: '图片尺寸最大宽度1024' }),
|
||||
(0, class_validator_1.Min)(512, { message: '图片尺寸最小宽度512' }),
|
||||
__metadata("design:type", Object)
|
||||
], StableDrawDto.prototype, "width", void 0);
|
||||
__decorate([
|
||||
(0, swagger_1.ApiProperty)({ example: 512, default: 512, description: '图片尺寸高度' }),
|
||||
(0, class_validator_1.Max)(1024, { message: '图片高度尺寸最大宽度1024' }),
|
||||
(0, class_validator_1.Min)(512, { message: '图片高度尺寸最小宽度512' }),
|
||||
__metadata("design:type", Object)
|
||||
], StableDrawDto.prototype, "height", void 0);
|
||||
__decorate([
|
||||
(0, swagger_1.ApiProperty)({ example: 15, default: 7, description: '图片绘制扩散思维[值越高,图像越接近提示]', required: true }),
|
||||
(0, class_validator_1.Max)(35, { message: '扩散思维值最大为35' }),
|
||||
(0, class_validator_1.Min)(0, { message: '扩散思维值最小为0' }),
|
||||
__metadata("design:type", Object)
|
||||
], StableDrawDto.prototype, "cfg_scale", void 0);
|
||||
__decorate([
|
||||
(0, swagger_1.ApiProperty)({ example: 50, description: '绘制步骤', required: true }),
|
||||
(0, class_validator_1.Max)(150, { message: '最大步骤不大于150' }),
|
||||
(0, class_validator_1.Min)(10, { message: '步骤不小于10' }),
|
||||
__metadata("design:type", Object)
|
||||
], StableDrawDto.prototype, "steps", void 0);
|
||||
__decorate([
|
||||
(0, swagger_1.ApiProperty)({ example: 'anime', description: '样式预设', required: true }),
|
||||
(0, class_validator_1.IsIn)([
|
||||
'3d-model',
|
||||
'analog-film',
|
||||
'anime',
|
||||
'cinematic',
|
||||
'comic-book',
|
||||
'digital-art',
|
||||
'enhance',
|
||||
'fantasy-art',
|
||||
'isometric',
|
||||
'line-art',
|
||||
'low-poly',
|
||||
'modeling-compound',
|
||||
'neon-punk',
|
||||
'origami',
|
||||
'photographic',
|
||||
'pixel-art',
|
||||
'tile-texture',
|
||||
]),
|
||||
__metadata("design:type", String)
|
||||
], StableDrawDto.prototype, "style_preset", void 0);
|
||||
__decorate([
|
||||
(0, swagger_1.ApiProperty)({ example: 'NONE', description: '裁剪指南预设', required: true }),
|
||||
(0, class_validator_1.IsIn)(['NONE', 'FAST_BLUE', 'FAST_GREEN', 'SIMPLE', 'SLOW', 'SLOWER', 'SLOWEST']),
|
||||
__metadata("design:type", Object)
|
||||
], StableDrawDto.prototype, "clip_guidance_preset", void 0);
|
||||
exports.StableDrawDto = StableDrawDto;
|
||||
@@ -13,15 +13,15 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.GlobalConfigService = void 0;
|
||||
const models_service_1 = require("./../models/models.service");
|
||||
const chatLog_entity_1 = require("./../chatLog/chatLog.entity");
|
||||
const common_1 = require("@nestjs/common");
|
||||
const config_entity_1 = require("./config.entity");
|
||||
const typeorm_1 = require("@nestjs/typeorm");
|
||||
const typeorm_2 = require("typeorm");
|
||||
const utils_1 = require("../../common/utils");
|
||||
const common_1 = require("@nestjs/common");
|
||||
const typeorm_1 = require("@nestjs/typeorm");
|
||||
const axios_1 = require("axios");
|
||||
const fs = require("fs");
|
||||
const typeorm_2 = require("typeorm");
|
||||
const chatLog_entity_1 = require("./../chatLog/chatLog.entity");
|
||||
const models_service_1 = require("./../models/models.service");
|
||||
const config_entity_1 = require("./config.entity");
|
||||
const packageJsonContent = fs.readFileSync('package.json', 'utf-8');
|
||||
const packageJson = JSON.parse(packageJsonContent);
|
||||
const version = packageJson.version;
|
||||
@@ -356,7 +356,7 @@ let GlobalConfigService = class GlobalConfigService {
|
||||
};
|
||||
}
|
||||
getNamespace() {
|
||||
return process.env.NAMESPACE || 'NINEAI';
|
||||
return process.env.NAMESPACE || 'AIWeb';
|
||||
}
|
||||
async getSignatureGiftConfig() {
|
||||
const { signInStatus = 0, signInModel3Count = 0, signInModel4Count = 0, signInMjDrawToken = 0, } = await this.getConfigs(['signInStatus', 'signInModel3Count', 'signInModel4Count', 'signInMjDrawToken']);
|
||||
|
||||
@@ -6,16 +6,11 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
|
||||
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.DrawModule = void 0;
|
||||
exports.KnowledgeBaseController = void 0;
|
||||
const common_1 = require("@nestjs/common");
|
||||
const draw_controller_1 = require("./draw.controller");
|
||||
const draw_service_1 = require("./draw.service");
|
||||
let DrawModule = class DrawModule {
|
||||
let KnowledgeBaseController = class KnowledgeBaseController {
|
||||
};
|
||||
DrawModule = __decorate([
|
||||
(0, common_1.Module)({
|
||||
controllers: [draw_controller_1.DrawController],
|
||||
providers: [draw_service_1.DrawService],
|
||||
})
|
||||
], DrawModule);
|
||||
exports.DrawModule = DrawModule;
|
||||
KnowledgeBaseController = __decorate([
|
||||
(0, common_1.Controller)('knowledgeBase')
|
||||
], KnowledgeBaseController);
|
||||
exports.KnowledgeBaseController = KnowledgeBaseController;
|
||||
17
dist/modules/knowledgeBase/knowledgeBase.entity.js
vendored
Normal file
17
dist/modules/knowledgeBase/knowledgeBase.entity.js
vendored
Normal file
@@ -0,0 +1,17 @@
|
||||
"use strict";
|
||||
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
||||
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
||||
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
||||
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
||||
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.KnowledgeBaseEntity = void 0;
|
||||
const typeorm_1 = require("typeorm");
|
||||
const baseEntity_1 = require("../../common/entity/baseEntity");
|
||||
let KnowledgeBaseEntity = class KnowledgeBaseEntity extends baseEntity_1.BaseEntity {
|
||||
};
|
||||
KnowledgeBaseEntity = __decorate([
|
||||
(0, typeorm_1.Entity)({ name: 'knowledge_base' })
|
||||
], KnowledgeBaseEntity);
|
||||
exports.KnowledgeBaseEntity = KnowledgeBaseEntity;
|
||||
26
dist/modules/knowledgeBase/knowledgeBase.module.js
vendored
Normal file
26
dist/modules/knowledgeBase/knowledgeBase.module.js
vendored
Normal file
@@ -0,0 +1,26 @@
|
||||
"use strict";
|
||||
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
||||
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
||||
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
||||
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
||||
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.KnowledgeBaseModule = void 0;
|
||||
const common_1 = require("@nestjs/common");
|
||||
const knowledgeBase_controller_1 = require("./knowledgeBase.controller");
|
||||
const knowledgeBase_service_1 = require("./knowledgeBase.service");
|
||||
const typeorm_1 = require("@nestjs/typeorm");
|
||||
const knowledgeBase_entity_1 = require("./knowledgeBase.entity");
|
||||
let KnowledgeBaseModule = class KnowledgeBaseModule {
|
||||
};
|
||||
KnowledgeBaseModule = __decorate([
|
||||
(0, common_1.Global)(),
|
||||
(0, common_1.Module)({
|
||||
imports: [typeorm_1.TypeOrmModule.forFeature([knowledgeBase_entity_1.KnowledgeBaseEntity])],
|
||||
providers: [knowledgeBase_service_1.KnowledgeBaseService],
|
||||
controllers: [knowledgeBase_controller_1.KnowledgeBaseController],
|
||||
exports: [knowledgeBase_service_1.KnowledgeBaseService],
|
||||
})
|
||||
], KnowledgeBaseModule);
|
||||
exports.KnowledgeBaseModule = KnowledgeBaseModule;
|
||||
16
dist/modules/knowledgeBase/knowledgeBase.service.js
vendored
Normal file
16
dist/modules/knowledgeBase/knowledgeBase.service.js
vendored
Normal file
@@ -0,0 +1,16 @@
|
||||
"use strict";
|
||||
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
||||
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
||||
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
||||
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
||||
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.KnowledgeBaseService = void 0;
|
||||
const common_1 = require("@nestjs/common");
|
||||
let KnowledgeBaseService = class KnowledgeBaseService {
|
||||
};
|
||||
KnowledgeBaseService = __decorate([
|
||||
(0, common_1.Injectable)()
|
||||
], KnowledgeBaseService);
|
||||
exports.KnowledgeBaseService = KnowledgeBaseService;
|
||||
30
dist/modules/mailer/mailer.module.js
vendored
30
dist/modules/mailer/mailer.module.js
vendored
@@ -1,30 +0,0 @@
|
||||
"use strict";
|
||||
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
||||
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
||||
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
||||
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
||||
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
||||
};
|
||||
var MailerModule_1;
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.MailerModule = void 0;
|
||||
const common_1 = require("@nestjs/common");
|
||||
const nestjs_config_1 = require("nestjs-config");
|
||||
const mailer_1 = require("@nestjs-modules/mailer");
|
||||
const mailer_service_1 = require("./mailer.service");
|
||||
let MailerModule = MailerModule_1 = class MailerModule {
|
||||
};
|
||||
MailerModule = MailerModule_1 = __decorate([
|
||||
(0, common_1.Module)({
|
||||
imports: [
|
||||
nestjs_config_1.ConfigModule,
|
||||
mailer_1.MailerModule.forRootAsync({
|
||||
useFactory: (config) => config.get('mailer'),
|
||||
inject: [nestjs_config_1.ConfigService],
|
||||
}),
|
||||
],
|
||||
exports: [MailerModule_1],
|
||||
providers: [mailer_service_1.MailerService],
|
||||
})
|
||||
], MailerModule);
|
||||
exports.MailerModule = MailerModule;
|
||||
47
dist/modules/mailer/mailer.service.js
vendored
47
dist/modules/mailer/mailer.service.js
vendored
@@ -10,24 +10,59 @@ var __metadata = (this && this.__metadata) || function (k, v) {
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.MailerService = void 0;
|
||||
const mailer_1 = require("@nestjs-modules/mailer");
|
||||
const common_1 = require("@nestjs/common");
|
||||
const nodemailer = require("nodemailer");
|
||||
const globalConfig_service_1 = require("../globalConfig/globalConfig.service");
|
||||
let MailerService = class MailerService {
|
||||
constructor(mailerService) {
|
||||
this.mailerService = mailerService;
|
||||
constructor(globalConfigService) {
|
||||
this.globalConfigService = globalConfigService;
|
||||
}
|
||||
async sendMail(options) {
|
||||
try {
|
||||
await this.mailerService.sendMail(options);
|
||||
const configs = await this.globalConfigService.getConfigs([
|
||||
'MAILER_HOST',
|
||||
'MAILER_PORT',
|
||||
'MAILER_USER',
|
||||
'MAILER_PASS',
|
||||
'MAILER_SECURE',
|
||||
'siteName',
|
||||
'siteUrl',
|
||||
]);
|
||||
const html = `
|
||||
<div style="font-family: Helvetica, Arial, sans-serif; max-width: 500px; margin: auto; padding: 40px; background-color: #ffffff; border-radius: 12px; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);">
|
||||
<h2 style="text-align: center; color: #111; font-weight: 400;">验证您的邮箱</h2>
|
||||
<hr style="border: none; border-top: 1px solid #eaeaea; margin: 30px 0;">
|
||||
<div style="text-align: center; margin-bottom: 30px;">
|
||||
<span style="display: inline-block; font-size: 42px; font-weight: 700; padding: 10px 20px; background-color: #f5f5f5; border-radius: 10px;">${options.context.code}</span>
|
||||
</div>
|
||||
<p style="font-size: 16px; color: #111; text-align: center; line-height: 1.5;">此验证码将在 10 分钟后失效,非本人操作请忽略。</p>
|
||||
<hr style="border: none; border-top: 1px solid #eaeaea; margin: 30px 0;">
|
||||
<p style="font-size: 14px; color: #999; text-align: center;">点击访问:<a href="${configs.siteUrl}" style="color: #007AFF; text-decoration: none;">${configs.siteName}</a></p>
|
||||
</div>`;
|
||||
const transporter = nodemailer.createTransport({
|
||||
host: configs.MAILER_HOST,
|
||||
port: configs.MAILER_PORT,
|
||||
secure: (configs.MAILER_SECURE === '1') ? true : false,
|
||||
auth: {
|
||||
user: configs.MAILER_USER,
|
||||
pass: configs.MAILER_PASS,
|
||||
},
|
||||
});
|
||||
await transporter.sendMail({
|
||||
from: configs.MAILER_USER,
|
||||
to: options.to,
|
||||
subject: `验证码${options.context.code}`,
|
||||
html: html,
|
||||
});
|
||||
}
|
||||
catch (error) {
|
||||
console.log('error: ', error);
|
||||
console.error('error: ', error);
|
||||
throw new common_1.HttpException('邮件发送失败!', common_1.HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
};
|
||||
MailerService = __decorate([
|
||||
(0, common_1.Injectable)(),
|
||||
__metadata("design:paramtypes", [mailer_1.MailerService])
|
||||
__metadata("design:paramtypes", [globalConfig_service_1.GlobalConfigService])
|
||||
], MailerService);
|
||||
exports.MailerService = MailerService;
|
||||
|
||||
60
dist/modules/midjourney/midjourney.service.js
vendored
60
dist/modules/midjourney/midjourney.service.js
vendored
@@ -13,22 +13,22 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.MidjourneyService = void 0;
|
||||
const user_entity_1 = require("./../user/user.entity");
|
||||
const midjourney_constant_1 = require("../../common/constants/midjourney.constant");
|
||||
const common_1 = require("@nestjs/common");
|
||||
const typeorm_1 = require("@nestjs/typeorm");
|
||||
const midjourney_entity_1 = require("./midjourney.entity");
|
||||
const typeorm_2 = require("typeorm");
|
||||
const axios_1 = require("axios");
|
||||
const typeorm_2 = require("typeorm");
|
||||
const globalConfig_service_1 = require("../globalConfig/globalConfig.service");
|
||||
const models_service_1 = require("../models/models.service");
|
||||
const midjourney_constant_1 = require("../../common/constants/midjourney.constant");
|
||||
const upload_service_1 = require("../upload/upload.service");
|
||||
const userBalance_service_1 = require("../userBalance/userBalance.service");
|
||||
const user_entity_1 = require("./../user/user.entity");
|
||||
const midjourney_entity_1 = require("./midjourney.entity");
|
||||
const utils_1 = require("../../common/utils");
|
||||
const redisCache_service_1 = require("../redisCache/redisCache.service");
|
||||
const prompt_entity_1 = require("./prompt.entity");
|
||||
const userBalance_service_1 = require("../userBalance/userBalance.service");
|
||||
const image_size_1 = require("image-size");
|
||||
const uuid = require("uuid");
|
||||
const redisCache_service_1 = require("../redisCache/redisCache.service");
|
||||
const prompt_entity_1 = require("./prompt.entity");
|
||||
let MidjourneyService = class MidjourneyService {
|
||||
constructor(midjourneyEntity, userEntity, mjPromptsEntity, globalConfigService, uploadService, userBalanceService, redisCacheService, modelsService) {
|
||||
this.midjourneyEntity = midjourneyEntity;
|
||||
@@ -118,38 +118,42 @@ let MidjourneyService = class MidjourneyService {
|
||||
let cosUrl = '';
|
||||
let isSaveImg = true;
|
||||
common_1.Logger.log(`绘制成功, 获取到的URL: ${imageUrl}`, 'MidjourneyService');
|
||||
if (mjNotSaveImg == 1 && mjNotUseProxy == 0) {
|
||||
let processedUrl = imageUrl;
|
||||
const shouldReplaceUrl = mjNotUseProxy === '0' && mjProxyImgUrl;
|
||||
let logMessage = '';
|
||||
if (shouldReplaceUrl) {
|
||||
const newUrlBase = new URL(mjProxyImgUrl);
|
||||
const parsedUrl = new URL(imageUrl);
|
||||
parsedUrl.protocol = newUrlBase.protocol;
|
||||
parsedUrl.hostname = newUrlBase.hostname;
|
||||
cosUrl = parsedUrl.toString();
|
||||
common_1.Logger.log(`替换后的 URL: ${cosUrl}`, 'MidjourneyService');
|
||||
parsedUrl.port = newUrlBase.port ? newUrlBase.port : '';
|
||||
processedUrl = parsedUrl.toString();
|
||||
logMessage = `使用代理替换后的 URL: ${processedUrl}`;
|
||||
common_1.Logger.log(logMessage, 'MidjourneyService');
|
||||
}
|
||||
else if (mjNotSaveImg == 1 && mjNotUseProxy == 1) {
|
||||
cosUrl = imageUrl;
|
||||
isSaveImg = false;
|
||||
common_1.Logger.log('使用原始图片链接', 'MidjourneyService');
|
||||
}
|
||||
else {
|
||||
if (mjNotSaveImg !== '1') {
|
||||
try {
|
||||
common_1.Logger.debug(`------> 开始上传图片!!!`);
|
||||
const filename = `${Date.now()}-${uuid.v4().slice(0, 4)}.png`;
|
||||
common_1.Logger.debug(`------> 开始上传图片!!!`, 'MidjourneyService');
|
||||
cosUrl = await this.uploadService.uploadFileFromUrl({ filename, url: imageUrl });
|
||||
common_1.Logger.log(`上传成功 URL: ${cosUrl}`, 'MidjourneyService');
|
||||
processedUrl = await this.uploadService.uploadFileFromUrl({ filename, url: processedUrl });
|
||||
logMessage = `上传成功 URL: ${processedUrl}`;
|
||||
}
|
||||
catch (uploadError) {
|
||||
common_1.Logger.error('存储图片失败,使用原始图片链接', 'MidjourneyService');
|
||||
isSaveImg = false;
|
||||
cosUrl = imageUrl;
|
||||
common_1.Logger.error('存储图片失败,使用原始/代理图片链接');
|
||||
logMessage = `存储图片失败,使用原始/代理图片链接 ${processedUrl}`;
|
||||
}
|
||||
common_1.Logger.log(logMessage, 'MidjourneyService');
|
||||
}
|
||||
const { width, height } = await this.getImageSizeFromUrl(imageUrl);
|
||||
else {
|
||||
logMessage = `不保存图片,使用 URL: ${processedUrl}`;
|
||||
common_1.Logger.log(logMessage, 'MidjourneyService');
|
||||
}
|
||||
const { width, height } = await this.getImageSizeFromUrl(processedUrl);
|
||||
const drawInfo = {
|
||||
status: midjourney_constant_1.MidjourneyStatusEnum.DRAWED,
|
||||
drawId: id,
|
||||
action: action,
|
||||
drawUrl: cosUrl,
|
||||
drawUrl: processedUrl,
|
||||
drawRatio: `${width}x${height}`,
|
||||
progress: 100,
|
||||
extend: JSON.stringify(drawRes),
|
||||
@@ -213,13 +217,15 @@ let MidjourneyService = class MidjourneyService {
|
||||
}
|
||||
async pollComparisonResultDraw(id, modelInfo, drawInfo) {
|
||||
const { key, proxyUrl, timeout } = modelInfo;
|
||||
const { openaiTimeout, } = await this.globalConfigService.getConfigs([
|
||||
const { openaiTimeout, openaiBaseUrl, openaiBaseKey, } = await this.globalConfigService.getConfigs([
|
||||
'openaiTimeout',
|
||||
'openaiBaseUrl',
|
||||
'openaiBaseKey',
|
||||
]);
|
||||
const effectiveTimeout = Math.max(timeout || openaiTimeout || 300, 300);
|
||||
const TIMEOUT = effectiveTimeout * 1000;
|
||||
const mjProxyUrl = proxyUrl;
|
||||
const mjKey = key;
|
||||
const mjProxyUrl = proxyUrl || openaiBaseUrl;
|
||||
const mjKey = key || openaiBaseKey;
|
||||
const startTime = Date.now();
|
||||
const POLL_INTERVAL = 5000;
|
||||
let pollingCount = 0;
|
||||
|
||||
76
dist/modules/models/modelType.entity.js
vendored
76
dist/modules/models/modelType.entity.js
vendored
@@ -1,76 +0,0 @@
|
||||
"use strict";
|
||||
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
||||
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
||||
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
||||
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
||||
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
||||
};
|
||||
var __metadata = (this && this.__metadata) || function (k, v) {
|
||||
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ModelsTypeEntity = void 0;
|
||||
const typeorm_1 = require("typeorm");
|
||||
const baseEntity_1 = require("../../common/entity/baseEntity");
|
||||
let ModelsTypeEntity = class ModelsTypeEntity extends baseEntity_1.BaseEntity {
|
||||
};
|
||||
__decorate([
|
||||
(0, typeorm_1.Column)({ comment: 'key模型类型 1: openai 2: 文心一言 3:清华智谱' }),
|
||||
__metadata("design:type", Number)
|
||||
], ModelsTypeEntity.prototype, "keyType", void 0);
|
||||
__decorate([
|
||||
(0, typeorm_1.Column)({ comment: '模型名称[给用户看的]' }),
|
||||
__metadata("design:type", String)
|
||||
], ModelsTypeEntity.prototype, "modelName", void 0);
|
||||
__decorate([
|
||||
(0, typeorm_1.Column)({ comment: '是否开放模型: 0:禁用 1:启用', default: 1 }),
|
||||
__metadata("design:type", Boolean)
|
||||
], ModelsTypeEntity.prototype, "status", void 0);
|
||||
__decorate([
|
||||
(0, typeorm_1.Column)({ comment: '绑定使用的模型是?最终调用的' }),
|
||||
__metadata("design:type", String)
|
||||
], ModelsTypeEntity.prototype, "model", void 0);
|
||||
__decorate([
|
||||
(0, typeorm_1.Column)({ comment: '模型温度0-2直接', default: 0.6 }),
|
||||
__metadata("design:type", Number)
|
||||
], ModelsTypeEntity.prototype, "temperature", void 0);
|
||||
__decorate([
|
||||
(0, typeorm_1.Column)({ comment: '模型的使用次数', default: 0 }),
|
||||
__metadata("design:type", Number)
|
||||
], ModelsTypeEntity.prototype, "useCount", void 0);
|
||||
__decorate([
|
||||
(0, typeorm_1.Column)({ comment: '模型总计使用的token数量', default: 0 }),
|
||||
__metadata("design:type", Number)
|
||||
], ModelsTypeEntity.prototype, "useToken", void 0);
|
||||
__decorate([
|
||||
(0, typeorm_1.Column)({ comment: '模型排序', default: 1 }),
|
||||
__metadata("design:type", Number)
|
||||
], ModelsTypeEntity.prototype, "modelOrder", void 0);
|
||||
__decorate([
|
||||
(0, typeorm_1.Column)({ comment: '单词调用扣除的次数', default: 1 }),
|
||||
__metadata("design:type", Number)
|
||||
], ModelsTypeEntity.prototype, "deduct", void 0);
|
||||
__decorate([
|
||||
(0, typeorm_1.Column)({ comment: '扣除余额类型 1: 普通模型 2:高级模型', default: 1 }),
|
||||
__metadata("design:type", Number)
|
||||
], ModelsTypeEntity.prototype, "deductType", void 0);
|
||||
__decorate([
|
||||
(0, typeorm_1.Column)({ comment: '模型设置允许用户使用的最大回复Token', default: 2048 }),
|
||||
__metadata("design:type", Number)
|
||||
], ModelsTypeEntity.prototype, "maxResponseTokens", void 0);
|
||||
__decorate([
|
||||
(0, typeorm_1.Column)({ comment: '限制用户上下文可选最大轮次数', nullable: true }),
|
||||
__metadata("design:type", Number)
|
||||
], ModelsTypeEntity.prototype, "maxRounds", void 0);
|
||||
__decorate([
|
||||
(0, typeorm_1.Column)({ comment: '是否为绘画模型Dall-E3', default: 0 }),
|
||||
__metadata("design:type", Boolean)
|
||||
], ModelsTypeEntity.prototype, "isDallE3", void 0);
|
||||
__decorate([
|
||||
(0, typeorm_1.Column)({ comment: '是否为特殊模型、可以提供联想翻译、思维导图等特殊操作', default: 0 }),
|
||||
__metadata("design:type", Boolean)
|
||||
], ModelsTypeEntity.prototype, "isUseTool", void 0);
|
||||
ModelsTypeEntity = __decorate([
|
||||
(0, typeorm_1.Entity)({ name: 'models_type' })
|
||||
], ModelsTypeEntity);
|
||||
exports.ModelsTypeEntity = ModelsTypeEntity;
|
||||
4
dist/modules/models/models.entity.js
vendored
4
dist/modules/models/models.entity.js
vendored
@@ -98,6 +98,10 @@ __decorate([
|
||||
(0, typeorm_1.Column)({ comment: '当前模型的代理地址', nullable: true }),
|
||||
__metadata("design:type", String)
|
||||
], ModelsEntity.prototype, "proxyUrl", void 0);
|
||||
__decorate([
|
||||
(0, typeorm_1.Column)({ comment: '模型频率限制 次/小时', default: 999 }),
|
||||
__metadata("design:type", Number)
|
||||
], ModelsEntity.prototype, "modelLimits", void 0);
|
||||
ModelsEntity = __decorate([
|
||||
(0, typeorm_1.Entity)({ name: 'models' })
|
||||
], ModelsEntity);
|
||||
|
||||
3
dist/modules/models/models.module.js
vendored
3
dist/modules/models/models.module.js
vendored
@@ -12,13 +12,12 @@ const models_controller_1 = require("./models.controller");
|
||||
const models_service_1 = require("./models.service");
|
||||
const typeorm_1 = require("@nestjs/typeorm");
|
||||
const models_entity_1 = require("./models.entity");
|
||||
const modelType_entity_1 = require("./modelType.entity");
|
||||
let ModelsModule = class ModelsModule {
|
||||
};
|
||||
ModelsModule = __decorate([
|
||||
(0, common_1.Global)(),
|
||||
(0, common_1.Module)({
|
||||
imports: [typeorm_1.TypeOrmModule.forFeature([models_entity_1.ModelsEntity, modelType_entity_1.ModelsTypeEntity])],
|
||||
imports: [typeorm_1.TypeOrmModule.forFeature([models_entity_1.ModelsEntity])],
|
||||
controllers: [models_controller_1.ModelsController],
|
||||
providers: [models_service_1.ModelsService],
|
||||
exports: [models_service_1.ModelsService]
|
||||
|
||||
18
dist/modules/models/models.service.js
vendored
18
dist/modules/models/models.service.js
vendored
@@ -13,17 +13,15 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ModelsService = void 0;
|
||||
const status_constant_1 = require("../../common/constants/status.constant");
|
||||
const utils_1 = require("../../common/utils");
|
||||
const common_1 = require("@nestjs/common");
|
||||
const typeorm_1 = require("@nestjs/typeorm");
|
||||
const typeorm_2 = require("typeorm");
|
||||
const models_entity_1 = require("./models.entity");
|
||||
const status_constant_1 = require("../../common/constants/status.constant");
|
||||
const utils_1 = require("../../common/utils");
|
||||
const modelType_entity_1 = require("./modelType.entity");
|
||||
let ModelsService = class ModelsService {
|
||||
constructor(modelsEntity, modelsTypeEntity) {
|
||||
constructor(modelsEntity) {
|
||||
this.modelsEntity = modelsEntity;
|
||||
this.modelsTypeEntity = modelsTypeEntity;
|
||||
this.modelTypes = [];
|
||||
this.modelMaps = {};
|
||||
this.keyList = {};
|
||||
@@ -97,12 +95,8 @@ let ModelsService = class ModelsService {
|
||||
async getBaseConfig(appId) {
|
||||
if (!this.modelTypes.length || !Object.keys(this.modelMaps).length)
|
||||
return;
|
||||
const modelTypeInfo = this.modelTypes[0];
|
||||
if (!modelTypeInfo)
|
||||
return;
|
||||
const { keyType, modelName, model, deductType, deduct, isFileUpload } = this.modelMaps[modelTypeInfo.val][0];
|
||||
const { keyType, modelName, model, deductType, deduct, isFileUpload } = this.modelMaps[1][0];
|
||||
return {
|
||||
modelTypeInfo,
|
||||
modelInfo: { keyType, modelName, model, deductType, deduct, isFileUpload }
|
||||
};
|
||||
}
|
||||
@@ -238,8 +232,6 @@ let ModelsService = class ModelsService {
|
||||
ModelsService = __decorate([
|
||||
(0, common_1.Injectable)(),
|
||||
__param(0, (0, typeorm_1.InjectRepository)(models_entity_1.ModelsEntity)),
|
||||
__param(1, (0, typeorm_1.InjectRepository)(modelType_entity_1.ModelsTypeEntity)),
|
||||
__metadata("design:paramtypes", [typeorm_2.Repository,
|
||||
typeorm_2.Repository])
|
||||
__metadata("design:paramtypes", [typeorm_2.Repository])
|
||||
], ModelsService);
|
||||
exports.ModelsService = ModelsService;
|
||||
|
||||
26
dist/modules/official/official.service.js
vendored
26
dist/modules/official/official.service.js
vendored
@@ -10,15 +10,15 @@ var __metadata = (this && this.__metadata) || function (k, v) {
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.OfficialService = void 0;
|
||||
const chat_service_1 = require("../chat/chat.service");
|
||||
const globalConfig_service_1 = require("./../globalConfig/globalConfig.service");
|
||||
const auth_service_1 = require("./../auth/auth.service");
|
||||
const user_service_1 = require("./../user/user.service");
|
||||
const autoreply_service_1 = require("./../autoreply/autoreply.service");
|
||||
const common_1 = require("@nestjs/common");
|
||||
const crypto = require("crypto");
|
||||
const axios_1 = require("axios");
|
||||
const utils_1 = require("../../common/utils");
|
||||
const common_1 = require("@nestjs/common");
|
||||
const axios_1 = require("axios");
|
||||
const crypto = require("crypto");
|
||||
const chat_service_1 = require("../chat/chat.service");
|
||||
const auth_service_1 = require("./../auth/auth.service");
|
||||
const autoreply_service_1 = require("./../autoreply/autoreply.service");
|
||||
const globalConfig_service_1 = require("./../globalConfig/globalConfig.service");
|
||||
const user_service_1 = require("./../user/user.service");
|
||||
let OfficialService = class OfficialService {
|
||||
constructor(autoreplyService, userService, authService, globalConfigService, chatgptService) {
|
||||
this.autoreplyService = autoreplyService;
|
||||
@@ -149,15 +149,7 @@ let OfficialService = class OfficialService {
|
||||
reject(new Error('请求超时'));
|
||||
}, 4800);
|
||||
});
|
||||
let question = '';
|
||||
try {
|
||||
console.log('来自公众号的询问问题 =======> ', msg);
|
||||
question = await this.autoreplyService.checkAutoReply(msg);
|
||||
}
|
||||
catch (error) {
|
||||
console.log('来自公众号的回复问题 =======> 超时导致问题无法回答完整');
|
||||
question = (await this.globalConfigService.getConfigs(['officialAutoReplyText'])) || '由于公众号的回复限制、过长的问题我们可能无法回复、您可以前往我们的官方站点享受更加完善的服务、如果您有更多问题、欢迎像我提问!';
|
||||
}
|
||||
let question = (await this.globalConfigService.getConfigs(['officialAutoReplyText'])) || '由于公众号的回复限制、过长的问题我们可能无法回复、您可以前往我们的官方站点享受更加完善的服务、如果您有更多问题、欢迎像我提问!';
|
||||
return question;
|
||||
}
|
||||
};
|
||||
|
||||
96
dist/modules/pay/pay.service.js
vendored
96
dist/modules/pay/pay.service.js
vendored
@@ -13,17 +13,17 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.PayService = void 0;
|
||||
const typeorm_1 = require("@nestjs/typeorm");
|
||||
const typeorm_2 = require("typeorm");
|
||||
const common_1 = require("@nestjs/common");
|
||||
const crypto = require("crypto");
|
||||
const axios_1 = require("axios");
|
||||
const order_entity_1 = require("../order/order.entity");
|
||||
const cramiPackage_entity_1 = require("../crami/cramiPackage.entity");
|
||||
const userBalance_service_1 = require("../userBalance/userBalance.service");
|
||||
const globalConfig_service_1 = require("../globalConfig/globalConfig.service");
|
||||
const utils_1 = require("../../common/utils");
|
||||
const common_1 = require("@nestjs/common");
|
||||
const typeorm_1 = require("@nestjs/typeorm");
|
||||
const axios_1 = require("axios");
|
||||
const crypto = require("crypto");
|
||||
const typeorm_2 = require("typeorm");
|
||||
const cramiPackage_entity_1 = require("../crami/cramiPackage.entity");
|
||||
const globalConfig_service_1 = require("../globalConfig/globalConfig.service");
|
||||
const order_entity_1 = require("../order/order.entity");
|
||||
const user_service_1 = require("../user/user.service");
|
||||
const userBalance_service_1 = require("../userBalance/userBalance.service");
|
||||
let PayService = class PayService {
|
||||
constructor(cramiPackageEntity, orderEntity, userBalanceService, globalConfigService, userService) {
|
||||
this.cramiPackageEntity = cramiPackageEntity;
|
||||
@@ -331,7 +331,7 @@ let PayService = class PayService {
|
||||
}
|
||||
}
|
||||
async payWeChat(userId, orderId, payType = 'native') {
|
||||
var _a, _b, _c;
|
||||
var _a, _b, _c, _d, _e, _f, _g;
|
||||
console.log('payType: ', payType);
|
||||
const order = await this.orderEntity.findOne({ where: { userId, orderId } });
|
||||
if (!order)
|
||||
@@ -361,46 +361,60 @@ let PayService = class PayService {
|
||||
out_trade_no: orderId,
|
||||
notify_url: payWeChatNotifyUrl,
|
||||
amount: {
|
||||
total: Number(order.total * 100),
|
||||
},
|
||||
scene_info: {
|
||||
payer_client_ip: '192.168.1.100',
|
||||
total: Math.round(order.total * 100),
|
||||
},
|
||||
};
|
||||
console.log('wechat-pay: ', params);
|
||||
if (payType == 'h5') {
|
||||
params.scene_info.h5_info = {
|
||||
type: 'Wap',
|
||||
app_name: payWeChatH5Name,
|
||||
app_url: payWeChatH5Url,
|
||||
};
|
||||
const res = await pay.transactions_h5(params);
|
||||
if (res.status === 403) {
|
||||
const errmsg = (_c = (_b = (_a = res === null || res === void 0 ? void 0 : res.errRaw) === null || _a === void 0 ? void 0 : _a.response) === null || _b === void 0 ? void 0 : _b.text) === null || _c === void 0 ? void 0 : _c.message;
|
||||
throw new common_1.HttpException((res === null || res === void 0 ? void 0 : res.message) || '微信H5支付失败!', common_1.HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
const { h5_url } = res;
|
||||
return { url: h5_url };
|
||||
}
|
||||
if (payType == 'jsapi') {
|
||||
console.log(`[WeChat Pay JSAPI] 开始JSAPI支付流程,用户ID: ${userId}, 订单ID: ${orderId}`);
|
||||
const openid = await this.userService.getOpenIdByUserId(userId);
|
||||
console.log('用户openId: ', openid);
|
||||
params['payer'] = {
|
||||
openid: openid,
|
||||
};
|
||||
const result = await pay.transactions_jsapi(params);
|
||||
console.log('jsapi支付结果返回值: ', result);
|
||||
return result;
|
||||
console.log(`[WeChat Pay JSAPI] 用户OpenID: ${openid}`);
|
||||
params['payer'] = { openid: openid };
|
||||
console.log(`[WeChat Pay JSAPI] 发送支付请求参数: `, JSON.stringify(params, null, 2));
|
||||
try {
|
||||
const response = await pay.transactions_jsapi(params);
|
||||
const result = response.data ? response.data : response;
|
||||
console.log(`[WeChat Pay JSAPI] 支付请求成功,返回结果: `, JSON.stringify(result, null, 2));
|
||||
return {
|
||||
status: response.status || 'unknown',
|
||||
appId: result.appId || ((_a = result.data) === null || _a === void 0 ? void 0 : _a.appId),
|
||||
timeStamp: result.timeStamp || ((_b = result.data) === null || _b === void 0 ? void 0 : _b.timeStamp),
|
||||
nonceStr: result.nonceStr || ((_c = result.data) === null || _c === void 0 ? void 0 : _c.nonceStr),
|
||||
package: result.package || ((_d = result.data) === null || _d === void 0 ? void 0 : _d.package),
|
||||
signType: result.signType || ((_e = result.data) === null || _e === void 0 ? void 0 : _e.signType),
|
||||
paySign: result.paySign || ((_f = result.data) === null || _f === void 0 ? void 0 : _f.paySign)
|
||||
};
|
||||
}
|
||||
catch (error) {
|
||||
console.error(`[WeChat Pay JSAPI] 支付请求过程中发生错误: ${error.message}`, error);
|
||||
console.error('[WeChat Pay JSAPI] 完整的错误对象:', error);
|
||||
throw new common_1.HttpException('JSAPI支付失败', common_1.HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
if (payType == 'native') {
|
||||
const res = await pay.transactions_native(params);
|
||||
const { code_url: url_qrcode } = res;
|
||||
if (!url_qrcode) {
|
||||
console.log('wx-native', res);
|
||||
console.log(`开始进行微信Native支付流程,订单ID: ${orderId}, 用户ID: ${userId}`);
|
||||
try {
|
||||
const res = await pay.transactions_native(params);
|
||||
console.log(`微信Native支付响应数据: `, JSON.stringify(res, null, 2));
|
||||
let url_qrcode = res.code_url || ((_g = res.data) === null || _g === void 0 ? void 0 : _g.code_url);
|
||||
if (!url_qrcode) {
|
||||
console.error(`微信Native支付请求成功,但未返回code_url,响应数据: `, JSON.stringify(res, null, 2));
|
||||
}
|
||||
else {
|
||||
console.log(`微信Native支付请求成功,code_url: ${url_qrcode}`);
|
||||
}
|
||||
return { url_qrcode, isRedirect: false };
|
||||
}
|
||||
catch (error) {
|
||||
console.error(`微信Native支付过程中发生错误,错误信息: ${error.message}`, error);
|
||||
console.error('完整的错误对象:', error);
|
||||
throw new common_1.HttpException('微信Native支付失败', common_1.HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
return { url_qrcode, isRedirect: false };
|
||||
}
|
||||
throw new common_1.HttpException('unsupported pay type', common_1.HttpStatus.BAD_REQUEST);
|
||||
else {
|
||||
console.warn(`支付请求使用了不支持的支付类型: ${payType}`);
|
||||
throw new common_1.HttpException('unsupported pay type', common_1.HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
async queryWeChat(orderId) {
|
||||
const { payWeChatAppId, payWeChatMchId, payWeChatPublicKey, payWeChatPrivateKey, payWeChatNotifyUrl, payWeChatH5Name, payWeChatH5Url } = await this.globalConfigService.getConfigs(['payWeChatAppId', 'payWeChatMchId', 'payWeChatPublicKey', 'payWeChatPrivateKey']);
|
||||
|
||||
6
dist/modules/queue/queue.service.js
vendored
6
dist/modules/queue/queue.service.js
vendored
@@ -13,12 +13,12 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.QueueService = void 0;
|
||||
const bull_1 = require("@nestjs/bull");
|
||||
const utils_1 = require("../../common/utils");
|
||||
const midjourney_service_1 = require("../midjourney/midjourney.service");
|
||||
const userBalance_service_1 = require("../userBalance/userBalance.service");
|
||||
const bull_1 = require("@nestjs/bull");
|
||||
const globalConfig_service_1 = require("../globalConfig/globalConfig.service");
|
||||
const midjourney_service_1 = require("../midjourney/midjourney.service");
|
||||
const models_service_1 = require("../models/models.service");
|
||||
const userBalance_service_1 = require("../userBalance/userBalance.service");
|
||||
let QueueService = class QueueService {
|
||||
constructor(mjDrawQueue, midjourneyService, userBalanceService, globalConfigService, modelsService) {
|
||||
this.mjDrawQueue = mjDrawQueue;
|
||||
|
||||
15
dist/modules/upload/upload.controller.js
vendored
15
dist/modules/upload/upload.controller.js
vendored
@@ -13,10 +13,10 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.UploadController = void 0;
|
||||
const upload_service_1 = require("./upload.service");
|
||||
const common_1 = require("@nestjs/common");
|
||||
const swagger_1 = require("@nestjs/swagger");
|
||||
const platform_express_1 = require("@nestjs/platform-express");
|
||||
const swagger_1 = require("@nestjs/swagger");
|
||||
const upload_service_1 = require("./upload.service");
|
||||
let UploadController = class UploadController {
|
||||
constructor(uploadService) {
|
||||
this.uploadService = uploadService;
|
||||
@@ -24,6 +24,9 @@ let UploadController = class UploadController {
|
||||
async uploadFile(file) {
|
||||
return this.uploadService.uploadFile(file);
|
||||
}
|
||||
async uploadFileFromUrl({ filename, url, dir = 'ai' }) {
|
||||
return this.uploadService.uploadFileFromUrl({ filename, url, dir });
|
||||
}
|
||||
};
|
||||
__decorate([
|
||||
(0, common_1.Post)('file'),
|
||||
@@ -34,6 +37,14 @@ __decorate([
|
||||
__metadata("design:paramtypes", [Object]),
|
||||
__metadata("design:returntype", Promise)
|
||||
], UploadController.prototype, "uploadFile", null);
|
||||
__decorate([
|
||||
(0, common_1.Post)('fileFromUrl'),
|
||||
(0, swagger_1.ApiOperation)({ summary: '从URL上传文件' }),
|
||||
__param(0, (0, common_1.Body)()),
|
||||
__metadata("design:type", Function),
|
||||
__metadata("design:paramtypes", [Object]),
|
||||
__metadata("design:returntype", Promise)
|
||||
], UploadController.prototype, "uploadFileFromUrl", null);
|
||||
UploadController = __decorate([
|
||||
(0, swagger_1.ApiTags)('upload'),
|
||||
(0, common_1.Controller)('upload'),
|
||||
|
||||
78
dist/modules/upload/upload.service.js
vendored
78
dist/modules/upload/upload.service.js
vendored
@@ -10,14 +10,16 @@ var __metadata = (this && this.__metadata) || function (k, v) {
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.UploadService = void 0;
|
||||
const utils_1 = require("../../common/utils");
|
||||
const common_1 = require("@nestjs/common");
|
||||
const TENCENTCOS = require("cos-nodejs-sdk-v5");
|
||||
const ALIOSS = require("ali-oss");
|
||||
const axios_1 = require("axios");
|
||||
const streamToBuffer = require("stream-to-buffer");
|
||||
const utils_1 = require("../../common/utils");
|
||||
const globalConfig_service_1 = require("../globalConfig/globalConfig.service");
|
||||
const TENCENTCOS = require("cos-nodejs-sdk-v5");
|
||||
const FormData = require("form-data");
|
||||
const fs = require("fs");
|
||||
const path_1 = require("path");
|
||||
const streamToBuffer = require("stream-to-buffer");
|
||||
const globalConfig_service_1 = require("../globalConfig/globalConfig.service");
|
||||
let UploadService = class UploadService {
|
||||
constructor(globalConfigService) {
|
||||
this.globalConfigService = globalConfigService;
|
||||
@@ -65,7 +67,7 @@ let UploadService = class UploadService {
|
||||
return 'chevereto';
|
||||
}
|
||||
}
|
||||
async uploadFileFromUrl({ filename, url, dir = 'mj' }) {
|
||||
async uploadFileFromUrl({ filename, url, dir = 'ai' }) {
|
||||
dir = process.env.ISDEV ? 'mjdev' : dir;
|
||||
const { tencentCosStatus = 0, aliOssStatus = 0, cheveretoStatus = 0, } = await this.globalConfigService.getConfigs(['tencentCosStatus', 'aliOssStatus', 'cheveretoStatus']);
|
||||
if (!Number(tencentCosStatus) && !Number(aliOssStatus) && !Number(cheveretoStatus)) {
|
||||
@@ -118,7 +120,6 @@ let UploadService = class UploadService {
|
||||
const { Bucket, Region, SecretId, SecretKey } = await this.getUploadConfig('tencent');
|
||||
this.tencentCos = new TENCENTCOS({ SecretId, SecretKey, FileParallelLimit: 10 });
|
||||
try {
|
||||
const proxyMj = (await this.globalConfigService.getConfigs(['mjProxy'])) || 0;
|
||||
const buffer = await this.getBufferFromUrl(url);
|
||||
return await this.uploadFileByTencentCos({ filename, buffer, dir, fileTyle: '' });
|
||||
}
|
||||
@@ -147,23 +148,40 @@ let UploadService = class UploadService {
|
||||
throw new common_1.HttpException('上传图片失败[ali]', common_1.HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
async uploadFileToLocalFromUrl({ filename, url, dir }) {
|
||||
try {
|
||||
const buffer = await this.getBufferFromUrl(url);
|
||||
return await this.uploadFileToLocal({ filename, buffer, dir });
|
||||
}
|
||||
catch (error) {
|
||||
console.log('TODO->error: ', error);
|
||||
throw new common_1.HttpException('上传图片失败[ten][url]', common_1.HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
async uploadFileToLocal({ filename, buffer, dir = 'ai' }) {
|
||||
if (!filename || !buffer) {
|
||||
throw new Error("必须提供文件名和文件内容");
|
||||
}
|
||||
const appRoot = require('app-root-path');
|
||||
const uploadDir = path_1.default.join(appRoot.path, 'service', 'public', 'file');
|
||||
const filePath = path_1.default.join(uploadDir, filename);
|
||||
if (!fs.existsSync(uploadDir)) {
|
||||
fs.mkdirSync(uploadDir, { recursive: true });
|
||||
common_1.Logger.log(`创建目录: ${uploadDir}`);
|
||||
}
|
||||
fs.writeFileSync(filePath, buffer);
|
||||
common_1.Logger.log(`文件已保存: ${filePath}`);
|
||||
const baseUrl = process.env.BASE_URL || 'http://127.0.0.1:9520';
|
||||
const fileUrl = `${baseUrl}/file/${filename}`;
|
||||
common_1.Logger.log(`文件可访问于: ${fileUrl}`);
|
||||
return fileUrl;
|
||||
}
|
||||
async uploadFileByAliOssFromUrl({ filename, url, dir }) {
|
||||
const { region, bucket, accessKeyId, accessKeySecret } = await this.getUploadConfig('ali');
|
||||
const client = new ALIOSS({ region, accessKeyId, accessKeySecret, bucket });
|
||||
try {
|
||||
const proxyMj = (await this.globalConfigService.getConfigs(['mjProxy'])) || 0;
|
||||
if (Number(proxyMj) === 1) {
|
||||
const data = { url, cosParams: { region, bucket, accessKeyId, accessKeySecret }, cosType: 'aliyun' };
|
||||
const mjProxyUrl = (await this.globalConfigService.getConfigs(['mjProxyUrl'])) || 'http://172.247.48.137:8000';
|
||||
const res = await axios_1.default.post(`${mjProxyUrl}/mj/replaceUpload`, data);
|
||||
if (!(res === null || res === void 0 ? void 0 : res.data))
|
||||
throw new common_1.HttpException('上传图片失败[ALI][url]', common_1.HttpStatus.BAD_REQUEST);
|
||||
return res.data;
|
||||
}
|
||||
else {
|
||||
const buffer = await this.getBufferFromUrl(url);
|
||||
return await this.uploadFileByAliOss({ filename, buffer, dir });
|
||||
}
|
||||
const buffer = await this.getBufferFromUrl(url);
|
||||
return await this.uploadFileByAliOss({ filename, buffer, dir });
|
||||
}
|
||||
catch (error) {
|
||||
throw new common_1.HttpException('上传图片失败[ALI][url]', common_1.HttpStatus.BAD_REQUEST);
|
||||
@@ -174,8 +192,10 @@ let UploadService = class UploadService {
|
||||
const { key, uploadPath } = await this.getUploadConfig('chevereto');
|
||||
let url = uploadPath.endsWith('/') ? uploadPath.slice(0, -1) : uploadPath;
|
||||
const formData = new FormData();
|
||||
formData.append('source', buffer);
|
||||
const fromBuffer = buffer.toString('base64');
|
||||
formData.append('source', fromBuffer);
|
||||
formData.append('key', key);
|
||||
formData.append('title', filename);
|
||||
try {
|
||||
const res = await axios_1.default.post(url, formData, {
|
||||
headers: { 'X-API-Key': key },
|
||||
@@ -195,21 +215,8 @@ let UploadService = class UploadService {
|
||||
}
|
||||
async uploadFileByCheveretoFromUrl({ filename, url, dir }) {
|
||||
try {
|
||||
const proxyMj = (await this.globalConfigService.getConfigs(['mjProxy'])) || 0;
|
||||
if (Number(proxyMj) === 1) {
|
||||
const { key, uploadPath } = await this.getUploadConfig('chevereto');
|
||||
let formatUploadPath = uploadPath.endsWith('/') ? uploadPath.slice(0, -1) : uploadPath;
|
||||
const data = { cosType: 'chevereto', url, cosParams: { key, uploadPath: formatUploadPath } };
|
||||
const mjProxyUrl = (await this.globalConfigService.getConfigs(['mjProxyUrl'])) || 'http://172.247.48.137:8000';
|
||||
const res = await axios_1.default.post(`${mjProxyUrl}/mj/replaceUpload`, data);
|
||||
if (!res.data)
|
||||
throw new common_1.HttpException('上传图片失败[Chevereto][url]', common_1.HttpStatus.BAD_REQUEST);
|
||||
return res.data;
|
||||
}
|
||||
else {
|
||||
const buffer = await this.getBufferFromUrl(url);
|
||||
return await this.uploadFileByChevereto({ filename, buffer, dir });
|
||||
}
|
||||
const buffer = await this.getBufferFromUrl(url);
|
||||
return await this.uploadFileByChevereto({ filename, buffer, dir });
|
||||
}
|
||||
catch (error) {
|
||||
console.log('error: ', error);
|
||||
@@ -234,7 +241,6 @@ let UploadService = class UploadService {
|
||||
}
|
||||
}
|
||||
async getBufferFromUrl(url) {
|
||||
const proxyMj = (await this.globalConfigService.getConfigs(['mjProxy'])) || 0;
|
||||
const response = await axios_1.default.get(url, { responseType: 'stream' });
|
||||
return new Promise((resolve, reject) => {
|
||||
streamToBuffer(response.data, (err, buffer) => {
|
||||
|
||||
18
dist/modules/user/user.controller.js
vendored
18
dist/modules/user/user.controller.js
vendored
@@ -13,19 +13,19 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.UserController = void 0;
|
||||
const user_service_1 = require("./user.service");
|
||||
const adminAuth_guard_1 = require("../../common/auth/adminAuth.guard");
|
||||
const jwtAuth_guard_1 = require("../../common/auth/jwtAuth.guard");
|
||||
const superAuth_guard_1 = require("../../common/auth/superAuth.guard");
|
||||
const common_1 = require("@nestjs/common");
|
||||
const swagger_1 = require("@nestjs/swagger");
|
||||
const updateUser_dto_1 = require("./dto/updateUser.dto");
|
||||
const jwtAuth_guard_1 = require("../../common/auth/jwtAuth.guard");
|
||||
const adminAuth_guard_1 = require("../../common/auth/adminAuth.guard");
|
||||
const userRecharge_dto_1 = require("./dto/userRecharge.dto");
|
||||
const queryAllUser_dto_1 = require("./dto/queryAllUser.dto");
|
||||
const queryOne_dto_1 = require("./dto/queryOne.dto");
|
||||
const updateUserStatus_dto_1 = require("./dto/updateUserStatus.dto");
|
||||
const resetUserPass_dto_1 = require("./dto/resetUserPass.dto");
|
||||
const superAuth_guard_1 = require("../../common/auth/superAuth.guard");
|
||||
const queryInviteRecord_dto_1 = require("./dto/queryInviteRecord.dto");
|
||||
const queryOne_dto_1 = require("./dto/queryOne.dto");
|
||||
const resetUserPass_dto_1 = require("./dto/resetUserPass.dto");
|
||||
const updateUser_dto_1 = require("./dto/updateUser.dto");
|
||||
const updateUserStatus_dto_1 = require("./dto/updateUserStatus.dto");
|
||||
const userRecharge_dto_1 = require("./dto/userRecharge.dto");
|
||||
const user_service_1 = require("./user.service");
|
||||
let UserController = class UserController {
|
||||
constructor(userService) {
|
||||
this.userService = userService;
|
||||
|
||||
33
dist/modules/user/user.module.js
vendored
33
dist/modules/user/user.module.js
vendored
@@ -7,26 +7,27 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.UserModule = void 0;
|
||||
const verifycation_entity_1 = require("./../verification/verifycation.entity");
|
||||
const verification_service_1 = require("./../verification/verification.service");
|
||||
const common_1 = require("@nestjs/common");
|
||||
const typeorm_1 = require("@nestjs/typeorm");
|
||||
const user_controller_1 = require("./user.controller");
|
||||
const user_service_1 = require("./user.service");
|
||||
const user_entity_1 = require("./user.entity");
|
||||
const userBalance_service_1 = require("../userBalance/userBalance.service");
|
||||
const balance_entity_1 = require("../userBalance/balance.entity");
|
||||
const accountLog_entity_1 = require("../userBalance/accountLog.entity");
|
||||
const config_entity_1 = require("../globalConfig/config.entity");
|
||||
const cramiPackage_entity_1 = require("../crami/cramiPackage.entity");
|
||||
const whiteList_entity_1 = require("../chat/whiteList.entity");
|
||||
const userBalance_entity_1 = require("../userBalance/userBalance.entity");
|
||||
const salesUsers_entity_1 = require("../sales/salesUsers.entity");
|
||||
const redisCache_service_1 = require("../redisCache/redisCache.service");
|
||||
const fingerprint_entity_1 = require("../userBalance/fingerprint.entity");
|
||||
const chatLog_entity_1 = require("../chatLog/chatLog.entity");
|
||||
const chatGroup_entity_1 = require("../chatGroup/chatGroup.entity");
|
||||
const chatLog_entity_1 = require("../chatLog/chatLog.entity");
|
||||
const cramiPackage_entity_1 = require("../crami/cramiPackage.entity");
|
||||
const config_entity_1 = require("../globalConfig/config.entity");
|
||||
const mailer_service_1 = require("../mailer/mailer.service");
|
||||
const midjourney_entity_1 = require("../midjourney/midjourney.entity");
|
||||
const redisCache_service_1 = require("../redisCache/redisCache.service");
|
||||
const salesUsers_entity_1 = require("../sales/salesUsers.entity");
|
||||
const accountLog_entity_1 = require("../userBalance/accountLog.entity");
|
||||
const balance_entity_1 = require("../userBalance/balance.entity");
|
||||
const fingerprint_entity_1 = require("../userBalance/fingerprint.entity");
|
||||
const userBalance_entity_1 = require("../userBalance/userBalance.entity");
|
||||
const userBalance_service_1 = require("../userBalance/userBalance.service");
|
||||
const verification_service_1 = require("./../verification/verification.service");
|
||||
const verifycation_entity_1 = require("./../verification/verifycation.entity");
|
||||
const user_controller_1 = require("./user.controller");
|
||||
const user_entity_1 = require("./user.entity");
|
||||
const user_service_1 = require("./user.service");
|
||||
let UserModule = class UserModule {
|
||||
};
|
||||
UserModule = __decorate([
|
||||
@@ -50,7 +51,7 @@ UserModule = __decorate([
|
||||
]),
|
||||
],
|
||||
controllers: [user_controller_1.UserController],
|
||||
providers: [user_service_1.UserService, verification_service_1.VerificationService, userBalance_service_1.UserBalanceService, redisCache_service_1.RedisCacheService],
|
||||
providers: [user_service_1.UserService, verification_service_1.VerificationService, userBalance_service_1.UserBalanceService, redisCache_service_1.RedisCacheService, mailer_service_1.MailerService,],
|
||||
exports: [user_service_1.UserService],
|
||||
})
|
||||
], UserModule);
|
||||
|
||||
79
dist/modules/user/user.service.js
vendored
79
dist/modules/user/user.service.js
vendored
@@ -13,22 +13,22 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.UserService = void 0;
|
||||
const globalConfig_service_1 = require("./../globalConfig/globalConfig.service");
|
||||
const user_constant_1 = require("./../../common/constants/user.constant");
|
||||
const mailer_1 = require("@nestjs-modules/mailer");
|
||||
const verification_service_1 = require("./../verification/verification.service");
|
||||
const balance_constant_1 = require("../../common/constants/balance.constant");
|
||||
const verification_constant_1 = require("../../common/constants/verification.constant");
|
||||
const utils_1 = require("../../common/utils");
|
||||
const mailer_service_1 = require("../mailer/mailer.service");
|
||||
const common_1 = require("@nestjs/common");
|
||||
const typeorm_1 = require("@nestjs/typeorm");
|
||||
const typeorm_2 = require("typeorm");
|
||||
const user_entity_1 = require("./user.entity");
|
||||
const bcrypt = require("bcryptjs");
|
||||
const _ = require("lodash");
|
||||
const verification_constant_1 = require("../../common/constants/verification.constant");
|
||||
const userBalance_service_1 = require("../userBalance/userBalance.service");
|
||||
const utils_1 = require("../../common/utils");
|
||||
const balance_constant_1 = require("../../common/constants/balance.constant");
|
||||
const config_entity_1 = require("../globalConfig/config.entity");
|
||||
const typeorm_2 = require("typeorm");
|
||||
const whiteList_entity_1 = require("../chat/whiteList.entity");
|
||||
const config_entity_1 = require("../globalConfig/config.entity");
|
||||
const userBalance_service_1 = require("../userBalance/userBalance.service");
|
||||
const user_constant_1 = require("./../../common/constants/user.constant");
|
||||
const globalConfig_service_1 = require("./../globalConfig/globalConfig.service");
|
||||
const verification_service_1 = require("./../verification/verification.service");
|
||||
const user_entity_1 = require("./user.entity");
|
||||
let UserService = class UserService {
|
||||
constructor(userEntity, whiteListEntity, connection, verificationService, mailerService, userBalanceService, globalConfigService, configEntity) {
|
||||
this.userEntity = userEntity;
|
||||
@@ -92,13 +92,7 @@ let UserService = class UserService {
|
||||
const { code, email, id } = v;
|
||||
const { registerVerifyEmailFrom } = configMap;
|
||||
console.log('configMap: ', configMap);
|
||||
const res = await this.mailerService.sendMail({
|
||||
to: email,
|
||||
subject: `来自${registerVerifyEmailFrom}的账号激活`,
|
||||
template: 'register',
|
||||
context: Object.assign({ baseUrl: configMap['registerBaseUrl'], code, id }, configMap),
|
||||
});
|
||||
console.log('email response -> : ', res);
|
||||
console.log(`尝试发送邮件到: ${email}`);
|
||||
}
|
||||
else {
|
||||
const { username, email, id, invitedBy } = n;
|
||||
@@ -133,17 +127,7 @@ let UserService = class UserService {
|
||||
}
|
||||
}
|
||||
if (username && password) {
|
||||
const where = [{ username }, { email: username }];
|
||||
u = await this.userEntity.findOne({ where: where });
|
||||
if (!u) {
|
||||
throw new common_1.HttpException('当前账户不存在!', common_1.HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
if (!bcrypt.compareSync(password, u.password)) {
|
||||
throw new common_1.HttpException('当前密码错误!', common_1.HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
if (phone && password) {
|
||||
const where = [{ phone }];
|
||||
const where = [{ username }, { email: username }, { phone: username }];
|
||||
u = await this.userEntity.findOne({ where: where });
|
||||
if (!u) {
|
||||
throw new common_1.HttpException('当前账户不存在!', common_1.HttpStatus.BAD_REQUEST);
|
||||
@@ -269,7 +253,7 @@ let UserService = class UserService {
|
||||
const [rows, count] = await this.userEntity.findAndCount({
|
||||
where: { invitedBy },
|
||||
order: { id: 'DESC' },
|
||||
select: ['username', 'email', 'createdAt', 'status', 'avatar'],
|
||||
select: ['username', 'email', 'createdAt', 'status', 'avatar', 'updatedAt'],
|
||||
take: size,
|
||||
skip: (page - 1) * size,
|
||||
});
|
||||
@@ -423,6 +407,25 @@ let UserService = class UserService {
|
||||
const user = await this.userEntity.findOne({ where: { id: userId } });
|
||||
return user === null || user === void 0 ? void 0 : user.openId;
|
||||
}
|
||||
async verifyUserRegister(params) {
|
||||
const { username, phone, email } = params;
|
||||
if (phone) {
|
||||
const userByPhone = await this.userEntity.findOne({ where: { phone } });
|
||||
if (userByPhone) {
|
||||
throw new common_1.HttpException('当前手机号已注册、请勿重复注册!', common_1.HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
if (email) {
|
||||
const userByEmail = await this.userEntity.findOne({ where: { email } });
|
||||
if (userByEmail) {
|
||||
throw new common_1.HttpException('当前邮箱已注册、请勿重复注册!', common_1.HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
const userByUsername = await this.userEntity.findOne({ where: { username } });
|
||||
if (userByUsername) {
|
||||
throw new common_1.HttpException('用户名已存在、请更换用户名!', common_1.HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
async verifyUserRegisterByPhone(params) {
|
||||
const { username, password, phone, phoneCode } = params;
|
||||
const user = await this.userEntity.findOne({ where: [{ username }, { phone }] });
|
||||
@@ -433,6 +436,20 @@ let UserService = class UserService {
|
||||
throw new common_1.HttpException('当前手机号已注册、请勿重复注册!', common_1.HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
async verifyUserRegisterByEmail(params) {
|
||||
const { username, email } = params;
|
||||
console.log(`校验邮箱注册: 开始 - 用户名: ${username}, 邮箱: ${email}`);
|
||||
const user = await this.userEntity.findOne({ where: [{ username }, { email }] });
|
||||
if (user && user.username === username) {
|
||||
console.error(`校验失败: 用户名 "${username}" 已存在`);
|
||||
throw new common_1.HttpException('用户名已存在、请更换用户名!', common_1.HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
if (user && user.email === email) {
|
||||
console.error(`校验失败: 邮箱 "${email}" 已被注册`);
|
||||
throw new common_1.HttpException('当前邮箱已注册、请勿重复注册!', common_1.HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
console.log(`校验邮箱注册: 成功 - 用户名: ${username}, 邮箱: ${email} 未被占用`);
|
||||
}
|
||||
async createUser(userInfo) {
|
||||
return await this.userEntity.save(userInfo);
|
||||
}
|
||||
@@ -446,7 +463,7 @@ UserService = __decorate([
|
||||
typeorm_2.Repository,
|
||||
typeorm_2.Connection,
|
||||
verification_service_1.VerificationService,
|
||||
mailer_1.MailerService,
|
||||
mailer_service_1.MailerService,
|
||||
userBalance_service_1.UserBalanceService,
|
||||
globalConfig_service_1.GlobalConfigService,
|
||||
typeorm_2.Repository])
|
||||
|
||||
@@ -17,7 +17,6 @@ const common_1 = require("@nestjs/common");
|
||||
const jwtAuth_guard_1 = require("../../common/auth/jwtAuth.guard");
|
||||
const swagger_1 = require("@nestjs/swagger");
|
||||
const userBalance_service_1 = require("./userBalance.service");
|
||||
const superAuth_guard_1 = require("../../common/auth/superAuth.guard");
|
||||
const adminAuth_guard_1 = require("../../common/auth/adminAuth.guard");
|
||||
let UserBalanceController = class UserBalanceController {
|
||||
constructor(userBalanceService) {
|
||||
@@ -32,9 +31,6 @@ let UserBalanceController = class UserBalanceController {
|
||||
async getBalance(req) {
|
||||
return this.userBalanceService.queryUserBalance(req.user.id);
|
||||
}
|
||||
async upgradeBalance() {
|
||||
return this.userBalanceService.upgradeBalance();
|
||||
}
|
||||
async inheritVisitorData(req) {
|
||||
return this.userBalanceService.inheritVisitorData(req);
|
||||
}
|
||||
@@ -74,15 +70,6 @@ __decorate([
|
||||
__metadata("design:paramtypes", [Object]),
|
||||
__metadata("design:returntype", Promise)
|
||||
], UserBalanceController.prototype, "getBalance", null);
|
||||
__decorate([
|
||||
(0, common_1.Post)('upgradeBalance'),
|
||||
(0, swagger_1.ApiOperation)({ summary: '升级V1.5 数据迁移job' }),
|
||||
(0, common_1.UseGuards)(superAuth_guard_1.SuperAuthGuard),
|
||||
(0, swagger_1.ApiBearerAuth)(),
|
||||
__metadata("design:type", Function),
|
||||
__metadata("design:paramtypes", []),
|
||||
__metadata("design:returntype", Promise)
|
||||
], UserBalanceController.prototype, "upgradeBalance", null);
|
||||
__decorate([
|
||||
(0, common_1.Post)('inheritVisitorData'),
|
||||
(0, swagger_1.ApiOperation)({ summary: '继承当前设备数据' }),
|
||||
|
||||
@@ -71,7 +71,7 @@ __decorate([
|
||||
__metadata("design:type", String)
|
||||
], UserBalanceEntity.prototype, "extent", void 0);
|
||||
__decorate([
|
||||
(0, typeorm_1.Column)({ comment: '会员到期时间 0:不是 1:是', nullable: true }),
|
||||
(0, typeorm_1.Column)({ comment: '会员到期时间', nullable: true }),
|
||||
__metadata("design:type", Date)
|
||||
], UserBalanceEntity.prototype, "expirationTime", void 0);
|
||||
UserBalanceEntity = __decorate([
|
||||
|
||||
24
dist/modules/userBalance/userBalance.service.js
vendored
24
dist/modules/userBalance/userBalance.service.js
vendored
@@ -13,26 +13,26 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.UserBalanceService = void 0;
|
||||
const globalConfig_service_1 = require("./../globalConfig/globalConfig.service");
|
||||
const typeorm_1 = require("@nestjs/typeorm");
|
||||
const balance_entity_1 = require("./balance.entity");
|
||||
const common_1 = require("@nestjs/common");
|
||||
const typeorm_2 = require("typeorm");
|
||||
const balance_constant_1 = require("../../common/constants/balance.constant");
|
||||
const accountLog_entity_1 = require("./accountLog.entity");
|
||||
const utils_1 = require("../../common/utils");
|
||||
const config_entity_1 = require("../globalConfig/config.entity");
|
||||
const common_1 = require("@nestjs/common");
|
||||
const typeorm_1 = require("@nestjs/typeorm");
|
||||
const typeorm_2 = require("typeorm");
|
||||
const cramiPackage_entity_1 = require("../crami/cramiPackage.entity");
|
||||
const config_entity_1 = require("../globalConfig/config.entity");
|
||||
const globalConfig_service_1 = require("./../globalConfig/globalConfig.service");
|
||||
const accountLog_entity_1 = require("./accountLog.entity");
|
||||
const balance_entity_1 = require("./balance.entity");
|
||||
const userBalance_entity_1 = require("./userBalance.entity");
|
||||
const date_1 = require("../../common/utils/date");
|
||||
const user_entity_1 = require("../user/user.entity");
|
||||
const salesUsers_entity_1 = require("../sales/salesUsers.entity");
|
||||
const sales_service_1 = require("../sales/sales.service");
|
||||
const whiteList_entity_1 = require("../chat/whiteList.entity");
|
||||
const fingerprint_entity_1 = require("./fingerprint.entity");
|
||||
const chatLog_entity_1 = require("../chatLog/chatLog.entity");
|
||||
const chatGroup_entity_1 = require("../chatGroup/chatGroup.entity");
|
||||
const chatLog_entity_1 = require("../chatLog/chatLog.entity");
|
||||
const midjourney_entity_1 = require("../midjourney/midjourney.entity");
|
||||
const sales_service_1 = require("../sales/sales.service");
|
||||
const salesUsers_entity_1 = require("../sales/salesUsers.entity");
|
||||
const user_entity_1 = require("../user/user.entity");
|
||||
const fingerprint_entity_1 = require("./fingerprint.entity");
|
||||
let UserBalanceService = class UserBalanceService {
|
||||
constructor(balanceEntity, userBalanceEntity, accountLogEntity, cramiPackageEntity, configEntity, userEntity, salesUsersEntity, whiteListEntity, fingerprintLogEntity, chatGroupEntity, chatLogEntity, midjourneyEntity, salesService, globalConfigService) {
|
||||
this.balanceEntity = balanceEntity;
|
||||
|
||||
@@ -13,14 +13,14 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.VerificationService = void 0;
|
||||
const utils_1 = require("../../common/utils");
|
||||
const globalConfig_service_1 = require("../globalConfig/globalConfig.service");
|
||||
const status_constant_1 = require("./../../common/constants/status.constant");
|
||||
const common_1 = require("@nestjs/common");
|
||||
const typeorm_1 = require("@nestjs/typeorm");
|
||||
const typeorm_2 = require("typeorm");
|
||||
const verifycation_entity_1 = require("./verifycation.entity");
|
||||
const common_1 = require("@nestjs/common");
|
||||
const utils_1 = require("../../common/utils");
|
||||
const redisCache_service_1 = require("../redisCache/redisCache.service");
|
||||
const status_constant_1 = require("./../../common/constants/status.constant");
|
||||
const verifycation_entity_1 = require("./verifycation.entity");
|
||||
const Core = require("@alicloud/pop-core");
|
||||
let VerificationService = class VerificationService {
|
||||
constructor(verifycationEntity, globalConfigService, redisCacheService) {
|
||||
@@ -76,6 +76,7 @@ let VerificationService = class VerificationService {
|
||||
async sendPhoneCode(messageInfo) {
|
||||
var _a;
|
||||
const { accessKeyId, accessKeySecret, SignName, TemplateCode } = await this.globalConfigService.getPhoneVerifyConfig();
|
||||
console.log("Received messageInfo:", messageInfo);
|
||||
const { phone, code } = messageInfo;
|
||||
if (!phone || !code) {
|
||||
throw new common_1.HttpException('确实必要参数错误!', common_1.HttpStatus.BAD_REQUEST);
|
||||
|
||||
Reference in New Issue
Block a user