-
Notifications
You must be signed in to change notification settings - Fork 125
/
Copy path对话1.txt
283 lines (233 loc) · 7.88 KB
/
对话1.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
我基于你的代码做了一些调整,接下来请更新记忆:
1. index2.js
import Fastify from 'fastify';
import * as drpy from './libs/drpy.js';
import path from 'path';
import {fileURLToPath} from 'url';
const fastify = Fastify({logger: true});
const __dirname = path.dirname(fileURLToPath(import.meta.url));
console.log('__dirname:', __dirname);
// 动态加载模块并根据 query 执行不同逻辑
fastify.get('/api/:module', async (request, reply) => {
const moduleName = request.params.module;
const query = request.query; // 获取 query 参数
const modulePath = path.join(__dirname, 'js', `${moduleName}.js`);
try {
// 根据 query 参数决定执行逻辑
if ('play' in query) {
// 处理播放逻辑
const result = await drpy.play(modulePath);
return reply.send(result);
}
if ('ac' in query && 't' in query) {
// 分类逻辑
const result = await drpy.cate(modulePath);
return reply.send(result);
}
if ('ac' in query && 'ids' in query) {
// 详情逻辑
const result = await drpy.detail(modulePath);
return reply.send(result);
}
if ('wd' in query) {
// 搜索逻辑
const result = await drpy.search(modulePath);
return reply.send(result);
}
if ('refresh' in query) {
// 强制刷新初始化逻辑
const refreshedObject = await drpy.init(modulePath, true);
return reply.send(refreshedObject);
}
// 默认逻辑,返回 home + homeVod 接口
const result_home = await drpy.home(modulePath);
const result_homeVod = await drpy.homeVod(modulePath);
const result = {
class: result_home,
list: result_homeVod
}
reply.send(result);
} catch (error) {
console.log('Error processing request:', error);
reply.status(500).send({error: `Failed to process request for module ${moduleName}: ${error.message}`});
}
});
// 启动服务
const start = async () => {
try {
await fastify.listen(5757);
console.log('Server listening at http://localhost:5757');
} catch (err) {
fastify.log.error(err);
process.exit(1);
}
};
start();
2. libs/drpy.js
import * as utils from '../utils/utils.js'; // 使用 import 引入工具类
import {readFile} from 'fs/promises';
import vm from 'vm'; // Node.js 的 vm 模块
const {req} = await import('../utils/req.js');
const {sleep, sleepSync} = await import('../utils/utils.js');
// 缓存已初始化的模块
const moduleCache = new Map();
/**
* 初始化模块:加载并执行模块文件,存储初始化后的 rule 对象
* 如果存在 `预处理` 属性且为函数,会在缓存前执行
* @param {string} filePath - 模块文件路径
* @param refresh 强制清除缓存
* @returns {Promise<object>} - 返回初始化后的模块对象
*/
export async function init(filePath, refresh) {
if (moduleCache.has(filePath) && !refresh) {
console.log(`Module ${filePath} already initialized, returning cached instance.`);
return moduleCache.get(filePath);
}
try {
let t1 = utils.getNowTime();
// 读取 JS 文件的内容
const fileContent = await readFile(filePath, 'utf-8');
// 创建一个沙箱上下文,注入需要的全局变量和函数
const sandbox = {
console,
req,
sleep,
sleepSync,
utils,
rule: {}, // 用于存放导出的 rule 对象
};
// 创建一个上下文
const context = vm.createContext(sandbox);
// 执行文件内容,将其放入沙箱中
const script = new vm.Script(fileContent);
script.runInContext(context);
// 访问沙箱中的 rule 对象
const moduleObject = utils.deepCopy(sandbox.rule);
// 检查并执行 `预处理` 方法
if (typeof moduleObject.预处理 === 'function') {
console.log('Executing preprocessing...');
await moduleObject.预处理();
}
// 缓存初始化后的模块
moduleCache.set(filePath, moduleObject);
let t2 = utils.getNowTime();
moduleObject.cost = t2 - t1;
return moduleObject;
} catch (error) {
console.log('Error in drpy.init:', error);
throw new Error('Failed to initialize module');
}
}
/**
* 调用模块的指定方法
* @param {string} filePath - 模块文件路径
* @param {string} method - 要调用的属性方法名称
* @returns {Promise<any>} - 方法调用的返回值
*/
async function invokeMethod(filePath, method) {
const moduleObject = await init(filePath); // 确保模块已初始化
if (moduleObject[method] && typeof moduleObject[method] === 'function') {
return await moduleObject[method](); // 调用对应的方法
} else {
throw new Error(`Method ${method} not found in module ${filePath}`);
}
}
// 各种接口调用方法
export async function home(filePath) {
return await invokeMethod(filePath, 'class_parse');
}
export async function homeVod(filePath) {
return await invokeMethod(filePath, '推荐');
}
export async function cate(filePath) {
return await invokeMethod(filePath, '一级');
}
export async function detail(filePath) {
return await invokeMethod(filePath, '二级');
}
export async function search(filePath) {
return await invokeMethod(filePath, '搜索');
}
export async function play(filePath) {
return await invokeMethod(filePath, 'lazy');
}
3.utils/req.js
export async function req(param) {
// 模拟异步请求
return new Promise((resolve) => {
setTimeout(() => {
resolve(`Response for ${param}`);
}, 1000);
});
}
4.utils/utils.js
// utils.js: 存放工具类方法
import pkg from 'lodash';
const {cloneDeep} = pkg;
export function getTitleLength(title) {
return title.length; // 返回标题长度
}
export function getNowTime() {
return (new Date()).getTime()
}
export async function sleep(ms) {
// 模拟异步请求
return new Promise((resolve) => {
setTimeout(() => {
resolve();
}, ms);
});
}
export function sleepSync(ms) {
const end = Date.now() + ms; // 获取当前时间并计算结束时间
while (Date.now() < end) {
// 阻塞式等待,直到时间到达
}
}
export const deepCopy = cloneDeep
5. js/_360.js
// js/_360.js
var rule = {
title: '标题1',
description: '这是描述',
category: '视频',
class_parse: async () => {
console.log('执行了分类获取')
return [
{type_id: '1', type_name: '电影'},
{type_id: '2', type_name: '电视剧'},
{type_id: '3', type_name: '综艺'},
{type_id: '4', type_name: '动漫'},
]
},
预处理: async () => {
console.log('执行了预处理')
rule.title = '360影视'
},
推荐: async () => {
sleepSync(2000);
console.log('进入了推荐')
// return '这是推荐:' + rule.title
return [
{vod_name: '测试电影1', vod_pic: '1.png', vod_remarks: '测试描述1', vod_id: 'http://www.1.com'},
{vod_name: '测试电影2', vod_pic: '2.png', vod_remarks: '测试描述2', vod_id: 'http://www.2.com'},
]
},
一级: async () => {
// await sleep(200);
sleepSync(200);
let html = await req('123');
console.log('title:', rule.title);
console.log('html:' + html);
return html + '\n' + '这是一级:' + rule.title
},
二级: async () => {
return '这是二级:' + rule.title
},
搜索: async () => {
return '这是搜索:' + rule.title
},
lazy: async () => {
return '这是播放:' + rule.title
},
};