Skip to content

Commit f34415c

Browse files
committed
update:更新一些细节,优化接口路由
1 parent 4d627ff commit f34415c

16 files changed

+457
-465
lines changed

Diff for: README.md

+3-2
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@
22

33
nodejs作为服务端的drpy实现。全面升级异步写法
44

5-
* [本地配置接口-动态](/config)
5+
* [本地配置接口-动态本地](/config)
6+
* [本地配置接口-动态外网/局域网](/config/1)
67
* [本地配置接口-静态](/index)
78

89
## 更新记录
@@ -35,4 +36,4 @@ todo:
3536

3637
## 参考资料
3738

38-
* [crypto-js-wasm使用教程](docs/crypto-js-wasm/readme-CN.md)
39+
* [crypto-js-wasm使用教程](docs/crypto-js-wasm/readme-CN.md)

Diff for: controllers/api.js

+27-15
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,38 @@
11
import path from 'path';
2-
import { existsSync } from 'fs';
3-
import { base64Decode } from '../libs_drpy/crypto-util.js';
2+
import {existsSync} from 'fs';
3+
import {base64Decode} from '../libs_drpy/crypto-util.js';
44
import * as drpy from '../libs/drpyS.js';
55

6-
export default (fastify, options) => {
6+
export default (fastify, options, done) => {
7+
// 动态加载模块并根据 query 执行不同逻辑
78
fastify.get('/api/:module', async (request, reply) => {
89
const moduleName = request.params.module;
9-
const query = request.query; // 获取查询参数
10+
const query = request.query; // 获取 query 参数
1011
const modulePath = path.join(options.jsDir, `${moduleName}.js`);
11-
1212
if (!existsSync(modulePath)) {
13-
reply.status(404).send({ error: `Module ${moduleName} not found` });
13+
reply.status(404).send({error: `Module ${moduleName} not found`});
1414
return;
1515
}
1616

1717
const pg = Number(query.pg) || 1;
18-
1918
try {
20-
// 根据查询参数的不同执行不同逻辑
19+
// 根据 query 参数决定执行逻辑
2120
if ('play' in query) {
22-
// 播放逻辑
21+
// 处理播放逻辑
2322
const result = await drpy.play(modulePath, query.flag, query.play);
2423
return reply.send(result);
2524
}
2625

2726
if ('ac' in query && 't' in query) {
27+
let ext = query.ext;
28+
let extend = {};
29+
if (ext) {
30+
try {
31+
extend = JSON.parse(base64Decode(ext))
32+
} catch (e) {
33+
}
34+
}
2835
// 分类逻辑
29-
const ext = query.ext ? base64Decode(query.ext) : null;
30-
const extend = ext ? JSON.parse(ext) : {};
3136
const result = await drpy.cate(modulePath, query.t, pg, 1, extend);
3237
return reply.send(result);
3338
}
@@ -46,12 +51,14 @@ export default (fastify, options) => {
4651
}
4752

4853
if ('refresh' in query) {
49-
// 强制刷新初始化
54+
// 强制刷新初始化逻辑
5055
const refreshedObject = await drpy.init(modulePath, true);
5156
return reply.send(refreshedObject);
5257
}
53-
54-
// 默认逻辑:`home` + `homeVod`
58+
if (!('filter' in query)) {
59+
query.filter = 1
60+
}
61+
// 默认逻辑,返回 home + homeVod 接口
5562
const filter = 'filter' in query ? query.filter : 1;
5663
const resultHome = await drpy.home(modulePath, filter);
5764
const resultHomeVod = await drpy.homeVod(modulePath);
@@ -61,9 +68,14 @@ export default (fastify, options) => {
6168
};
6269

6370
reply.send(result);
71+
6472
} catch (error) {
73+
// console.error('Error processing request:', error);
74+
// reply.status(500).send({error: `Failed to process request for module ${moduleName}: ${error.message}`});
75+
6576
fastify.log.error(`Error processing module ${moduleName}:`, error);
66-
reply.status(500).send({ error: `Failed to process module ${moduleName}: ${error.message}` });
77+
reply.status(500).send({error: `Failed to process module ${moduleName}: ${error.message}`});
6778
}
6879
});
80+
done();
6981
};

Diff for: controllers/config.js

+46-17
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,62 @@
1-
import { readdirSync, readFileSync, writeFileSync, existsSync } from 'fs';
1+
import {readdirSync, readFileSync, writeFileSync, existsSync} from 'fs';
22
import path from 'path';
33

4-
export default (fastify, options) => {
5-
fastify.get('/config', async (request, reply) => {
6-
const files = readdirSync(options.jsDir).filter((file) => file.endsWith('.js') && !file.startsWith('_'));
7-
const sites = files.map((file) => {
8-
const name = path.basename(file, '.js');
4+
// 工具函数:生成 JSON 数据
5+
function generateSiteJSON(jsDir, requestHost) {
6+
const files = readdirSync(jsDir);
7+
const sites = files
8+
.filter((file) => file.endsWith('.js') && !file.startsWith('_')) // 筛选出不是 "_" 开头的 .js 文件
9+
.map((file) => {
10+
const baseName = path.basename(file, '.js'); // 去掉文件扩展名
11+
const key = `drpyS_${baseName}`;
12+
const name = `${baseName}(drpyS)`;
13+
const api = `${requestHost}/api/${baseName}`; // 使用请求的 host 地址,避免硬编码端口
914
return {
10-
key: `drpyS_${name}`,
11-
name: `${name}(drpyS)`,
12-
type: 4,
13-
api: `http://127.0.0.1:${options.PORT}/api/${name}`,
14-
searchable: 1,
15-
ext: '',
15+
key,
16+
name,
17+
type: 4, // 固定值
18+
api,
19+
searchable: 1, // 固定值
20+
ext: "", // 固定为空字符串
1621
};
1722
});
23+
return {sites};
24+
}
1825

19-
const data = { sites };
20-
writeFileSync(options.indexFilePath, JSON.stringify(data, null, 2));
21-
reply.send(data);
22-
});
26+
export default (fastify, options, done) => {
2327

2428
fastify.get('/index', async (request, reply) => {
2529
if (!existsSync(options.indexFilePath)) {
26-
reply.code(404).send({ error: 'index.json not found' });
30+
reply.code(404).send({error: 'index.json not found'});
2731
return;
2832
}
2933

3034
const content = readFileSync(options.indexFilePath, 'utf-8');
3135
reply.send(JSON.parse(content));
3236
});
37+
38+
// 接口:返回配置 JSON,同时写入 index.json
39+
fastify.get('/config*', async (request, reply) => {
40+
const cfg_path = request.params['*']; // 捕获整个路径
41+
console.log(cfg_path);
42+
try {
43+
// 获取主机名,协议及端口
44+
const protocol = request.protocol; // http 或 https
45+
const hostname = request.hostname; // 主机名,不包含端口
46+
const port = request.socket.localPort; // 获取当前服务的端口
47+
console.log('port:', port);
48+
let requestHost = cfg_path === '/1' ? `${protocol}://${hostname}` : `http://127.0.0.1:${options.PORT}`; // 动态生成根地址
49+
const siteJSON = generateSiteJSON(options.jsDir, requestHost);
50+
const siteStr = JSON.stringify(siteJSON, null, 2);
51+
writeFileSync(options.indexFilePath, siteStr, 'utf8'); // 写入 index.json
52+
if (cfg_path === '/1') {
53+
writeFileSync(options.customFilePath, siteStr, 'utf8'); // 写入 index.json
54+
}
55+
reply.send(siteJSON);
56+
} catch (error) {
57+
reply.status(500).send({error: 'Failed to generate site JSON', details: error.message});
58+
}
59+
});
60+
61+
done();
3362
};

Diff for: controllers/docs.js

+89-14
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,97 @@
11
import path from 'path';
2-
import { existsSync, readFileSync } from 'fs';
2+
import {existsSync, readFileSync} from 'fs';
33
import '../utils/marked.min.js';
44

5-
export default (fastify, options) => {
5+
/**
6+
* 根据扩展名返回 MIME 类型
7+
* @param {string} ext 文件扩展名
8+
* @returns {string} MIME 类型
9+
*/
10+
function getMimeType(ext) {
11+
const mimeTypes = {
12+
'.txt': 'text/plain; charset=utf-8',
13+
'.html': 'text/html; charset=utf-8',
14+
'.css': 'text/css; charset=utf-8',
15+
'.js': 'application/javascript; charset=utf-8',
16+
'.json': 'application/json; charset=utf-8',
17+
'.jpg': 'image/jpeg',
18+
'.jpeg': 'image/jpeg',
19+
'.png': 'image/png',
20+
'.gif': 'image/gif',
21+
'.svg': 'image/svg+xml',
22+
'.pdf': 'application/pdf',
23+
};
24+
return mimeTypes[ext] || 'application/octet-stream';
25+
}
26+
27+
export default (fastify, options, done) => {
628
fastify.get('/docs/*', async (request, reply) => {
7-
const fullPath = path.resolve(options.docsDir, request.params['*']);
8-
if (!fullPath.startsWith(options.docsDir) || !existsSync(fullPath)) {
9-
reply.status(403).send('<h1>403 Forbidden</h1>');
10-
return;
11-
}
29+
const fullPath = request.params['*']; // 捕获整个路径
30+
console.log(`Request received for path: ${fullPath}`);
31+
try {
32+
const resolvedPath = path.resolve(options.docsDir, fullPath); // 将路径解析为绝对路径
33+
34+
// 确保 resolvedPath 在 docsDir 下
35+
if (!resolvedPath.startsWith(options.docsDir)) {
36+
reply.status(403).send(`<h1>403 Forbidden</h1><p>Access to the requested file is forbidden.</p>`);
37+
return;
38+
}
39+
fastify.log.info(`Resolved path: ${resolvedPath}`);
40+
41+
// 检查文件是否存在
42+
if (!existsSync(resolvedPath)) {
43+
reply.status(404).send(`<h1>404 Not Found</h1><p>File "${fullPath}" not found in /docs.</p>`);
44+
return;
45+
}
46+
47+
// 获取文件扩展名
48+
const ext = path.extname(resolvedPath).toLowerCase();
1249

13-
const ext = path.extname(fullPath).toLowerCase();
14-
if (ext === '.md') {
15-
const markdownContent = readFileSync(fullPath, 'utf8');
16-
const htmlContent = marked.parse(markdownContent);
17-
reply.type('text/html').send(htmlContent);
18-
} else {
19-
reply.sendFile(fullPath);
50+
if (ext === '.md') {
51+
// 处理 Markdown 文件
52+
const markdownContent = readFileSync(resolvedPath, 'utf8');
53+
const htmlContent = marked.parse(markdownContent);
54+
55+
reply.type('text/html').send(`
56+
<!DOCTYPE html>
57+
<html lang="en">
58+
<head>
59+
<meta charset="UTF-8">
60+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
61+
<title>${fullPath}</title>
62+
<style>
63+
body { font-family: Arial, sans-serif; line-height: 1.6; margin: 20px; padding: 0; }
64+
h1, h2, h3 { color: #333; }
65+
pre { background: #f4f4f4; padding: 10px; border-radius: 5px; }
66+
code { font-family: monospace; }
67+
</style>
68+
</head>
69+
<body>
70+
${htmlContent}
71+
</body>
72+
</html>
73+
`);
74+
} else {
75+
try {
76+
const mimeType = getMimeType(ext);
77+
78+
if (mimeType.startsWith('text') || mimeType.includes('json') || mimeType.includes('javascript')) {
79+
const fileContent = readFileSync(resolvedPath, 'utf8'); // 确保读取文本内容为 UTF-8
80+
reply.type(mimeType).send(fileContent);
81+
} else {
82+
const fileContent = readFileSync(resolvedPath);
83+
reply.type(mimeType).send(fileContent);
84+
}
85+
86+
} catch (e) {
87+
console.log(e);
88+
}
89+
}
90+
} catch (error) {
91+
reply.status(500).send(`<h1>500 Internal Server Error</h1><p>Error reading or rendering file: ${error.message}</p>`);
2092
}
2193
});
94+
95+
96+
done();
2297
};

Diff for: controllers/root.js

+29-16
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,45 @@
11
import path from 'path';
2-
import { readdirSync, readFileSync } from 'fs';
2+
import {readdirSync, readFileSync} from 'fs';
33
import '../utils/marked.min.js';
44

5-
export default (fastify, options) => {
5+
export default (fastify, options, done) => {
6+
// 添加 / 接口
67
fastify.get('/', async (request, reply) => {
7-
const files = readdirSync(options.docsDir);
8-
const readmePath = files.find((file) => /^readme\.md$/i.test(file)) ? path.join(options.docsDir, 'README.md') : null;
8+
let readmePath = null;
9+
const files = readdirSync(options.rootDir);
10+
for (const file of files) {
11+
if (/^readme\.md$/i.test(file)) {
12+
readmePath = path.join(options.rootDir, file);
13+
break;
14+
}
15+
}
916

17+
// 如果未找到 README.md 文件
1018
if (!readmePath) {
1119
reply.code(404).send('<h1>README.md not found</h1>');
1220
return;
1321
}
1422

23+
// 读取 README.md 文件内容
1524
const markdownContent = readFileSync(readmePath, 'utf-8');
25+
26+
// 将 Markdown 转换为 HTML
1627
const htmlContent = marked.parse(markdownContent);
1728

29+
// 返回 HTML 内容
1830
reply.type('text/html').send(`
19-
<!DOCTYPE html>
20-
<html lang="en">
21-
<head>
22-
<meta charset="UTF-8">
23-
<meta name="viewport" content="width=device-width, initial-scale=1.0">
24-
<title>README</title>
25-
</head>
26-
<body>
27-
${htmlContent}
28-
</body>
29-
</html>
30-
`);
31+
<!DOCTYPE html>
32+
<html lang="en">
33+
<head>
34+
<meta charset="UTF-8">
35+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
36+
<title>README</title>
37+
</head>
38+
<body>
39+
${htmlContent}
40+
</body>
41+
</html>
42+
`);
3143
});
44+
done();
3245
};

Diff for: custom.json

+4-4
Original file line numberDiff line numberDiff line change
@@ -4,31 +4,31 @@
44
"key": "drpyS_人人视频",
55
"name": "人人视频(drpyS)",
66
"type": 4,
7-
"api": "http://127.0.0.1:5757/api/人人视频",
7+
"api": "http://localhost:5757/api/人人视频",
88
"searchable": 1,
99
"ext": ""
1010
},
1111
{
1212
"key": "drpyS_星芽短剧",
1313
"name": "星芽短剧(drpyS)",
1414
"type": 4,
15-
"api": "http://127.0.0.1:5757/api/星芽短剧",
15+
"api": "http://localhost:5757/api/星芽短剧",
1616
"searchable": 1,
1717
"ext": ""
1818
},
1919
{
2020
"key": "drpyS_番茄小说[书]",
2121
"name": "番茄小说[书](drpyS)",
2222
"type": 4,
23-
"api": "http://127.0.0.1:5757/api/番茄小说[书]",
23+
"api": "http://localhost:5757/api/番茄小说[书]",
2424
"searchable": 1,
2525
"ext": ""
2626
},
2727
{
2828
"key": "drpyS_金牌影院",
2929
"name": "金牌影院(drpyS)",
3030
"type": 4,
31-
"api": "http://127.0.0.1:5757/api/金牌影院",
31+
"api": "http://localhost:5757/api/金牌影院",
3232
"searchable": 1,
3333
"ext": ""
3434
}

0 commit comments

Comments
 (0)