Skip to content

Commit 6db18f1

Browse files
author
Taois
committed
feat: 接口文件优化,修复上次发版的bug
1 parent a126867 commit 6db18f1

File tree

4 files changed

+171
-102
lines changed

4 files changed

+171
-102
lines changed

controllers/api.js

Lines changed: 26 additions & 76 deletions
Original file line numberDiff line numberDiff line change
@@ -1,46 +1,22 @@
1-
import path, { parse } from 'path';
2-
import {existsSync, watch} from 'fs';
1+
import path from 'path';
2+
import {existsSync} from 'fs';
33
import {base64Decode} from '../libs_drpy/crypto-util.js';
4+
import {ENV} from "../utils/env.js";
5+
import {validatePwd} from "../utils/api_validate.js";
6+
import {startJsonWatcher, getApiEngine} from "../utils/api_helper.js";
47
import * as drpy from '../libs/drpyS.js';
58
import * as drpy2 from '../libs/dr2Adapter.js';
69
import * as pyadapter from '../libs/pyAdapter.js';
7-
import {ENV} from "../utils/env.js";
8-
import {validatePwd} from "../utils/api_validate.js";
9-
10-
//添加JSON文件监听
11-
let jsonWatcher = null;
12-
let debounceTimers = new Map(); // 防抖计时器
13-
function startJsonWatcher(jsonDir) {
14-
if (process.env.NODE_ENV !== 'development') return;
15-
16-
try {
17-
jsonWatcher = watch(jsonDir, {recursive: true}, (eventType, filename) => {
18-
if (filename && filename.endsWith('.json')) {
19-
// 清除之前的计时器
20-
if (debounceTimers.has(filename)) {
21-
clearTimeout(debounceTimers.get(filename));
22-
}
2310

24-
// 设置新的防抖计时器
25-
const timer = setTimeout(() => {
26-
console.log(`${filename}文件已${eventType},即将清除所有模块缓存`);
27-
drpy.clearAllCache();
28-
debounceTimers.delete(filename);
29-
}, 100); // 100ms防抖延迟
30-
31-
debounceTimers.set(filename, timer);
32-
}
33-
});
34-
35-
console.log(`start json file hot reload success,listening path: ${jsonDir}`);
36-
} catch (error) {
37-
console.error('start json file listening failed with error:', error);
38-
}
39-
}
11+
const ENGINES = {
12+
drpy,
13+
drpy2,
14+
pyadapter,
15+
};
4016

4117
export default (fastify, options, done) => {
4218
// 启动JSON监听
43-
startJsonWatcher(options.jsonDir);
19+
startJsonWatcher(drpy, options.jsonDir);
4420

4521
// 动态加载模块并根据 query 执行不同逻辑
4622
fastify.route({
@@ -55,35 +31,8 @@ export default (fastify, options, done) => {
5531
const method = request.method.toUpperCase();
5632
// 根据请求方法选择参数来源
5733
const query = method === 'GET' ? request.query : request.body;
58-
let parseEngine;
59-
let _ext;
60-
let moduleDir;
61-
// 根据查询参数选择解析引擎和脚本路径(adpt=ds || dr || py)
62-
const adpt = query.adpt;
63-
switch (adpt) {
64-
case 'ds':
65-
parseEngine = drpy;
66-
moduleDir = options.jsDir;
67-
_ext ='.js';
68-
break;
69-
case 'dr':
70-
parseEngine = drpy2;
71-
moduleDir = options.dr2Dir;
72-
_ext ='.js';
73-
break;
74-
case 'py':
75-
parseEngine = pyadapter;
76-
moduleDir = options.pyDir;
77-
_ext ='.py';
78-
break;
79-
default:
80-
parseEngine = drpy;
81-
moduleDir = options.jsDir;
82-
_ext ='.js';
83-
break;
84-
}
85-
const modulePath = path.join(moduleDir, `${moduleName}${_ext}`);
86-
if (!existsSync(modulePath)) {
34+
let {apiEngine, moduleDir, _ext, modulePath} = getApiEngine(ENGINES, moduleName, query, options);
35+
if (!existsSync(modulePath)) {
8736
reply.status(404).send({error: `Module ${moduleName} not found`});
8837
return;
8938
}
@@ -129,7 +78,7 @@ export default (fastify, options, done) => {
12978
return null;
13079
}
13180
const _env = getEnv(_moduleName);
132-
const RULE = await parseEngine.getRule(_modulePath, _env);
81+
const RULE = await apiEngine.getRule(_modulePath, _env);
13382
RULE.callRuleFn = async function (_method, _args) {
13483
let invokeMethod = null;
13584
switch (_method) {
@@ -165,7 +114,7 @@ export default (fastify, options, done) => {
165114
return await RULE[_method]
166115
}
167116
}
168-
return await parseEngine[invokeMethod](_modulePath, _env, ..._args)
117+
return await apiEngine[invokeMethod](_modulePath, _env, ..._args)
169118
};
170119
return RULE
171120
};
@@ -175,7 +124,7 @@ export default (fastify, options, done) => {
175124
if ('play' in query) {
176125
// 处理播放逻辑
177126
// console.log('play query:', query);
178-
const result = await parseEngine.play(modulePath, env, query.flag, query.play);
127+
const result = await apiEngine.play(modulePath, env, query.flag, query.play);
179128
return reply.send(result);
180129
}
181130

@@ -191,7 +140,7 @@ export default (fastify, options, done) => {
191140
}
192141
}
193142
// 分类逻辑
194-
const result = await parseEngine.cate(modulePath, env, query.t, pg, 1, extend);
143+
const result = await apiEngine.cate(modulePath, env, query.t, pg, 1, extend);
195144
return reply.send(result);
196145
}
197146

@@ -200,36 +149,36 @@ export default (fastify, options, done) => {
200149
fastify.log.info(`[${moduleName}] 二级已接收post数据: ${query.ids}`);
201150
}
202151
// 详情逻辑
203-
const result = await parseEngine.detail(modulePath, env, query.ids.split(','));
152+
const result = await apiEngine.detail(modulePath, env, query.ids.split(','));
204153
return reply.send(result);
205154
}
206155

207156
if ('ac' in query && 'action' in query) {
208157
// 处理动作逻辑
209-
const result = await parseEngine.action(modulePath, env, query.action, query.value);
158+
const result = await apiEngine.action(modulePath, env, query.action, query.value);
210159
return reply.send(result);
211160
}
212161

213162

214163
if ('wd' in query) {
215164
// 搜索逻辑
216165
const quick = 'quick' in query ? query.quick : 0;
217-
const result = await parseEngine.search(modulePath, env, query.wd, quick, pg);
166+
const result = await apiEngine.search(modulePath, env, query.wd, quick, pg);
218167
return reply.send(result);
219168
}
220169

221170
if ('refresh' in query) {
222171
// 强制刷新初始化逻辑
223-
const refreshedObject = await parseEngine.init(modulePath, env, true);
172+
const refreshedObject = await apiEngine.init(modulePath, env, true);
224173
return reply.send(refreshedObject);
225174
}
226175
if (!('filter' in query)) {
227176
query.filter = 1
228177
}
229178
// 默认逻辑,返回 home + homeVod 接口
230179
const filter = 'filter' in query ? query.filter : 1;
231-
const resultHome = await parseEngine.home(modulePath, env, filter);
232-
const resultHomeVod = await parseEngine.homeVod(modulePath, env);
180+
const resultHome = await apiEngine.home(modulePath, env, filter);
181+
const resultHomeVod = await apiEngine.homeVod(modulePath, env);
233182
let result = {
234183
...resultHome,
235184
// list: resultHomeVod,
@@ -253,7 +202,8 @@ export default (fastify, options, done) => {
253202
fastify.get('/proxy/:module/*', async (request, reply) => {
254203
const moduleName = request.params.module;
255204
const query = request.query; // 获取 query 参数
256-
const modulePath = path.join(options.jsDir, `${moduleName}.js`);
205+
206+
let {apiEngine, modulePath} = getApiEngine(ENGINES, moduleName, query, options);
257207
if (!existsSync(modulePath)) {
258208
reply.status(404).send({error: `Module ${moduleName} not found`});
259209
return;
@@ -295,7 +245,7 @@ export default (fastify, options, done) => {
295245

296246
const env = getEnv(moduleName);
297247
try {
298-
const backRespList = await parseEngine.proxy(modulePath, env, query);
248+
const backRespList = await apiEngine.proxy(modulePath, env, query);
299249
const statusCode = backRespList[0];
300250
const mediaType = backRespList[1] || 'application/octet-stream';
301251
let content = backRespList[2] || '';

controllers/config.js

Lines changed: 25 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -189,7 +189,7 @@ async function generateSiteJSON(options, requestHost, sub, pwd) {
189189

190190
// 根据用户是否启用dr2源去生成对应配置
191191
const enable_dr2 = ENV.get('enable_dr2', '1');
192-
if ((enable_dr2 === '1' || enable_dr2 === '2') ) {
192+
if ((enable_dr2 === '1' || enable_dr2 === '2')) {
193193
const dr2_files = readdirSync(dr2Dir);
194194
let dr2_valid_files = dr2_files.filter((file) => file.endsWith('.js') && !file.startsWith('_')); // 筛选出不是 "_" 开头的 .js 文件
195195
// log(dr2_valid_files);
@@ -253,43 +253,43 @@ async function generateSiteJSON(options, requestHost, sub, pwd) {
253253

254254
fileSites.forEach((fileSite) => {
255255
if (enable_dr2 === '1') {
256-
// dr2ApiType=0 使用接口drpy2 dr2ApiType=1 使用壳子内置的drpy2
257-
let api = dr2ApiType ? `assets://js/lib/drpy2.js` : `${requestHost}/public/drpy/drpy2.min.js`;
258-
let ext = `${requestHost}/js/${file}`;
259-
if (pwd) {
260-
ext += `?pwd=${pwd}`;
261-
}
262-
// 处理传参源的ext
263-
if (fileSite.queryStr) {
264-
ext = updateQueryString(ext, fileSite.queryStr);
265-
}
266-
// 模式1:只启用dr2的T3配置
267-
const site = {
268-
key: fileSite.key,
269-
name: fileSite.name,
270-
type: 3, // 固定值
271-
api,
272-
...ruleMeta,
273-
ext: ext || "", // 固定为空字符串
274-
};
275-
sites.push(site);
256+
// dr2ApiType=0 使用接口drpy2 dr2ApiType=1 使用壳子内置的drpy2
257+
let api = dr2ApiType ? `assets://js/lib/drpy2.js` : `${requestHost}/public/drpy/drpy2.min.js`;
258+
let ext = `${requestHost}/js/${file}`;
259+
if (pwd) {
260+
ext += `?pwd=${pwd}`;
261+
}
262+
// 处理传参源的ext
263+
if (fileSite.queryStr) {
264+
ext = updateQueryString(ext, fileSite.queryStr);
265+
}
266+
// 模式1:只启用dr2的T3配置
267+
const site = {
268+
key: fileSite.key,
269+
name: fileSite.name,
270+
type: 3, // 固定值
271+
api,
272+
...ruleMeta,
273+
ext: ext || "", // 固定为空字符串
274+
};
275+
sites.push(site);
276276
} else if (enable_dr2 === '2') {
277277
// 模式2:只启用T3脚本的T4风格API配置
278278
const t4site = {
279279
key: fileSite.key,
280280
name: fileSite.name,
281281
type: 4, // 固定值
282-
api:`${requestHost}/api/${baseName}`,
282+
api: `${requestHost}/api/${baseName}`,
283283
...ruleMeta,
284284
ext: "", // 固定为空字符串
285285
};
286286
// 添加isdr2参数到API URL
287287
if (pwd) {
288-
t4site.api += `?pwd=${pwd}&adpt=dr`;
288+
t4site.api += `?pwd=${pwd}&adapt=dr`;
289289
} else {
290-
t4site.api += `?adpt=dr`;
290+
t4site.api += `?adapt=dr`;
291291
}
292-
292+
293293
// 处理传参源的API参数
294294
if (fileSite.queryStr) {
295295
const separator = t4site.api.includes('?') ? '&' : '?';

libs/pyAdapter.js

Lines changed: 56 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,56 @@
1-
//在线解析py源,能力有限,暂时不会
1+
//在线解析py源,能力有限,暂时不会
2+
const getRule = async function () {
3+
4+
}
5+
6+
const init = async function () {
7+
8+
}
9+
10+
const home = async function () {
11+
12+
}
13+
14+
const homeVod = async function () {
15+
16+
}
17+
18+
19+
const cate = async function () {
20+
21+
}
22+
23+
const detail = async function () {
24+
25+
}
26+
27+
28+
const search = async function () {
29+
30+
}
31+
32+
const play = async function () {
33+
34+
}
35+
36+
37+
const proxy = async function () {
38+
39+
}
40+
41+
const action = async function () {
42+
43+
}
44+
45+
export default {
46+
getRule,
47+
init,
48+
home,
49+
homeVod,
50+
cate,
51+
detail,
52+
search,
53+
play,
54+
proxy,
55+
action,
56+
}

utils/api_helper.js

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
import {watch} from 'fs';
2+
import path from 'path';
3+
4+
//添加JSON文件监听
5+
let jsonWatcher = null;
6+
let debounceTimers = new Map(); // 防抖计时器
7+
export function startJsonWatcher(drpy, jsonDir) {
8+
if (process.env.NODE_ENV !== 'development') return;
9+
10+
try {
11+
jsonWatcher = watch(jsonDir, {recursive: true}, (eventType, filename) => {
12+
if (filename && filename.endsWith('.json')) {
13+
// 清除之前的计时器
14+
if (debounceTimers.has(filename)) {
15+
clearTimeout(debounceTimers.get(filename));
16+
}
17+
18+
// 设置新的防抖计时器
19+
const timer = setTimeout(() => {
20+
console.log(`${filename}文件已${eventType},即将清除所有模块缓存`);
21+
drpy.clearAllCache();
22+
debounceTimers.delete(filename);
23+
}, 100); // 100ms防抖延迟
24+
25+
debounceTimers.set(filename, timer);
26+
}
27+
});
28+
29+
console.log(`start json file hot reload success,listening path: ${jsonDir}`);
30+
} catch (error) {
31+
console.error('start json file listening failed with error:', error);
32+
}
33+
}
34+
35+
export function getApiEngine(engines, moduleName, query, options) {
36+
const adapt = query.adapt;
37+
let apiEngine;
38+
let moduleDir;
39+
let _ext;
40+
41+
switch (adapt) {
42+
case 'dr':
43+
apiEngine = engines.drpy2;
44+
moduleDir = options.dr2Dir;
45+
_ext = '.js';
46+
break;
47+
case 'py':
48+
apiEngine = engines.pyadapter;
49+
moduleDir = options.pyDir;
50+
_ext = '.py';
51+
break;
52+
default:
53+
apiEngine = engines.drpy;
54+
moduleDir = options.jsDir;
55+
_ext = '.js';
56+
}
57+
const modulePath = path.join(moduleDir, `${moduleName}${_ext}`);
58+
return {
59+
apiEngine,
60+
moduleDir,
61+
_ext,
62+
modulePath,
63+
}
64+
}

0 commit comments

Comments
 (0)