doubaoserver/app.js

154 lines
4.2 KiB
JavaScript

/**
* Copyright 2025 Beijing Volcano Engine Technology Co., Ltd. All Rights Reserved.
* SPDX-license-identifier: BSD-3-Clause
*/
const Koa = require('koa');
const bodyParser = require('koa-bodyparser');
const cors = require('koa2-cors');
const { Signer } = require('@volcengine/openapi');
const fetch = require('node-fetch');
const AccessToken = require('./AccessToken');
const Privileges = require('./AccessToken').privileges;
const app = new Koa();
app.use(cors({
origin: '*'
}));
/**
* @notes 在 https://console.volcengine.com/iam/keymanage/ 获取 AK/SK
*/
const ACCOUNT_INFO = {
/**
* @notes 必填, 在 https://console.volcengine.com/iam/keymanage/ 获取
*/
accessKeyId: 'AKLTNGJhYTRiMWE5Yzc2NDhlODk3NzE0YTI4NzEyZTM3NDI',
/**
* @notes 必填, 在 https://console.volcengine.com/iam/keymanage/ 获取
*/
secretKey: 'T1RrellUVXpaRFU0WXpVME5EZzRNV0UxTXpObFl6QmhPVFl4TUdFME0yTQ==',
/**
* @notes 非必填, 主账号无须传入, 子账号须传, 获取方式可参考
* https://www.volcengine.com/docs/6348/1315561 中的 步骤 4-使用子账号调用智能体接口 一节
*/
// sessionToken: 'Your SessionToken',
}
// AccessToken 应用配置
const appID = "67e11a296ff39301ed7429aa";
const appKey = "51151bf3ab2545bbb1b1494ffaae0521";
app.use(bodyParser());
app.use(async ctx => {
/**
* @brief 代理 AIGC 的 OpenAPI 请求
*/
if (ctx.url.startsWith('/api/proxyaigc') && ctx.method.toLowerCase() === 'post') {
const { Action, Version = '2023-11-01' } = ctx.query || {};
const body = {
AppId: appID, // 自动添加 AppId
...ctx.request.body
};
const openApiRequestData = {
region: 'cn-north-1',
method: 'POST',
params: {
Action,
Version,
},
headers: {
Host: 'rtc.volcengineapi.com',
'Content-type': 'application/json',
Authorization: '',
},
body,
};
const signer = new Signer(openApiRequestData, "rtc");
signer.addAuthorization(ACCOUNT_INFO);
console.log('请求参数:', { Action, Version, body }); // 添加日志
const result = await fetch(`https://rtc.volcengineapi.com?Action=${Action}&Version=${Version}`, {
method: 'POST',
headers: {
...openApiRequestData.headers,
Authorization: openApiRequestData.headers.Authorization,
},
body: JSON.stringify(body),
});
const volcResponse = await result.json();
console.log('响应结果:', volcResponse); // 添加日志
if (!volcResponse.ResponseMetadata?.Error) {
ctx.body = volcResponse;
} else {
ctx.status = 500;
ctx.body = {
code: 500,
message: volcResponse.ResponseMetadata.Error.Message || '请求失败',
data: null
};
}
}
/**
* @brief 生成 token 的 API 接口
*/
else if (ctx.url === '/api/token' && ctx.method.toLowerCase() === 'post') {
try {
const { roomId, userId } = ctx.request.body;
// 参数验证
if (!roomId || !userId) {
ctx.status = 400;
ctx.body = {
code: 400,
message: '缺少必要参数 roomId 或 userId',
data: null
};
return;
}
// 创建 AccessToken
const key = new AccessToken.AccessToken(appID, appKey, roomId, userId);
// 添加权限
key.addPrivilege(Privileges.PrivSubscribeStream, 0);
key.addPrivilege(Privileges.PrivPublishStream, Math.floor(new Date() / 1000) + (24 * 3600));
key.expireTime(Math.floor(new Date() / 1000) + (24 * 3600));
// 序列化 token
const token = key.serialize();
// 返回成功响应
ctx.status = 200;
ctx.body = {
code: 200,
message: '获取 token 成功',
data: { token }
};
} catch (error) {
console.error('生成 token 出错:', error);
ctx.status = 500;
ctx.body = {
code: 500,
message: '服务器内部错误',
data: null
};
}
} else {
ctx.body = '<h1>404 Not Found</h1>';
}
});
app.listen(3001, () => {
console.log('AIGC Server is running at http://localhost:3001');
console.log('Token API is available at http://localhost:3001/api/token');
});