-
Notifications
You must be signed in to change notification settings - Fork 283
Expand file tree
/
Copy pathhipy.js
More file actions
297 lines (271 loc) · 10.4 KB
/
hipy.js
File metadata and controls
297 lines (271 loc) · 10.4 KB
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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
import path from "path";
import {readFile} from "fs/promises";
import {getSitesMap} from "../utils/sites-map.js";
import {computeHash, deepCopy, getNowTime} from "../utils/utils.js";
import {fileURLToPath} from 'url';
import {md5} from "../libs_drpy/crypto-util.js";
import {PythonShell, PythonShellError} from 'python-shell';
import {fastify} from "../controllers/fastlogger.js";
import {daemon} from "../utils/daemonManager.js";
// 缓存已初始化的模块和文件 hash 值
const moduleCache = new Map();
const ruleObjectCache = new Map();
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const _data_path = path.join(__dirname, '../data');
const _config_path = path.join(__dirname, '../config');
const _lib_path = path.join(__dirname, '../spider/py');
const timeout = 30000; // 30秒超时
const json2Object = function (json) {
// console.log('json2Object:', json);
if (!json) {
return {}
} else if (json && typeof json === 'object') {
return json
}
return JSON.parse(json);
}
const loadEsmWithHash = async function (filePath, fileHash, env) {
// 创建Python模块代理
const spiderProxy = {};
const bridgePath = path.join(_lib_path, '_bridge.py'); // 桥接脚本路径
// 创建方法调用函数
const callPythonMethodOld = async (methodName, env, ...args) => {
const options = {
mode: 'text', // 使用JSON模式自动解析
pythonOptions: ['-u'], // 无缓冲输出
// scriptPath: path.dirname(bridgePath),
timeout: timeout,
env: {
"PYTHONIOENCODING": 'utf-8',
}
};
// 将参数序列化为JSON字符串
const jsonArgs = args.map(arg => JSON.stringify(arg));
console.log(methodName, ...jsonArgs);
try {
const results = await PythonShell.run(bridgePath, {
...options,
args: [filePath, methodName, JSON.stringify(env), ...jsonArgs]
});
// 取最后一条返回
let vodResult = results.slice(-1)[0];
// if (methodName !== 'init') {
// console.log(vodResult);
// }
if (typeof vodResult === 'string' && vodResult) {
switch (vodResult) {
case 'None':
vodResult = null;
break;
case 'True':
vodResult = true;
break;
case 'False':
vodResult = false;
break;
default:
vodResult = JSON5.parse(vodResult);
break;
}
}
// console.log('hipy logs:', results.slice(0, -1));
fastify.log.info(`hipy logs: ${JSON.stringify(results.slice(0, -1))}`);
// fastify.log.info(`typeof vodResult: ${typeof vodResult}`);
// console.log('vodResult:', vodResult);
// 检查是否有错误
if (vodResult && vodResult.error) {
throw new Error(`Python错误: ${vodResult.error}\n${vodResult.traceback}`);
}
return vodResult; // 返回最后1个结果集
} catch (error) {
console.error('error:', error);
if (error instanceof PythonShellError) {
// 尝试解析Python的错误输出
try {
const errorData = JSON.parse(error.message);
throw new Error(`Python错误: ${errorData.error}\n${errorData.traceback}`);
} catch (e) {
throw new Error(`Python执行错误: ${error.message}`);
}
}
throw error;
}
};
const callPythonMethod = async (methodName, env, ...args) => {
const config = daemon.getDaemonConfig();
const command = [
`"${daemon.getPythonPath()}"`,
`"${config.clientScript}"`,
`--script-path "${filePath}"`,
`--method-name "${methodName}"`,
`--env '${JSON.stringify(env)}'`,
...args.map(arg => `--arg '${JSON.stringify(arg)}'`)
].join(' ');
// console.log(command);
const cmd_args = [];
args.forEach(arg => {
cmd_args.push(`--arg`);
cmd_args.push(`${JSON.stringify(arg)}`);
});
const options = {
mode: 'text',
pythonPath: daemon.getPythonPath(),
pythonOptions: ['-u'], // 无缓冲输出
env: {
"PYTHONIOENCODING": 'utf-8',
},
args: [
'--script-path', filePath,
'--method-name', methodName,
'--env', JSON.stringify(env),
...cmd_args
]
};
const results = await PythonShell.run(config.clientScript, {
...options,
});
// 取最后一条返回
const stdout = results.slice(-1)[0];
fastify.log.info(`hipy logs: ${JSON.stringify(results.slice(0, -1))}`);
// console.log(`hipy logs: ${JSON.stringify(results.slice(0, -1))}`);
let vodResult = {};
if (typeof stdout === 'string' && stdout) {
switch (stdout) {
case 'None':
vodResult = null;
break;
case 'True':
vodResult = true;
break;
case 'False':
vodResult = false;
break;
default:
vodResult = JSON5.parse(stdout);
break;
}
}
// console.log(typeof vodResult);
// 检查是否有错误
if (vodResult && vodResult.error) {
throw new Error(`Python错误: ${vodResult.error}\n${vodResult.traceback}`);
}
// console.log(vodResult);
return vodResult.result;
}
// 定义Spider类的方法
const spiderMethods = [
'init', 'home', 'homeVod', 'homeContent', 'category',
'detail', 'search', 'play', 'proxy', 'action', 'initEnv'
];
// 为代理对象添加方法
spiderMethods.forEach(method => {
spiderProxy[method] = async (...args) => {
return callPythonMethod(method, env, ...args);
};
});
// 处理initEnv调用
if (typeof spiderProxy.initEnv === 'function' && env) {
await spiderProxy.initEnv(env);
}
return spiderProxy;
}
const getRule = async function (filePath, env) {
const moduleObject = await init(filePath, env);
return JSON.stringify(moduleObject);
}
const init = async function (filePath, env = {}, refresh) {
try {
const fileContent = await readFile(filePath, 'utf-8');
const fileHash = computeHash(fileContent);
const moduleName = path.basename(filePath, '.js');
let moduleExt = env.ext || '';
const default_init_cfg = {
stype: 4, //T3/T4 源类型
skey: `hipy_${moduleName}`,
sourceKey: `hipy_${moduleName}`,
ext: moduleExt,
};
let SitesMap = getSitesMap(_config_path);
if (moduleExt && SitesMap[moduleName]) {
try {
moduleExt = ungzip(moduleExt);
} catch (e) {
log(`[${moduleName}] ungzip解密moduleExt失败: ${e.message}`);
}
if (!SitesMap[moduleName].find(i => i.queryStr === moduleExt) && !SitesMap[moduleName].find(i => i.queryObject.params === moduleExt)) {
throw new Error("moduleExt is wrong!")
}
}
let hashMd5 = md5(filePath + '#pAq#' + moduleExt);
if (moduleCache.has(hashMd5) && !refresh) {
const cached = moduleCache.get(hashMd5);
// 除hash外还必须保证proxyUrl实时相等,避免本地代理url的尴尬情况
if (cached.hash === fileHash && cached.proxyUrl === env.proxyUrl) {
// console.log('cached init');
return cached.moduleObject;
}
}
log(`Loading module: ${filePath}`);
let t1 = getNowTime();
let module;
module = await loadEsmWithHash(filePath, fileHash, env);
// console.log('module:', module);
const rule = module;
const initValue = await rule.init(default_init_cfg) || {};
let t2 = getNowTime();
const moduleObject = deepCopy(rule);
moduleObject.cost = t2 - t1;
moduleCache.set(hashMd5, {moduleObject, hash: fileHash, proxyUrl: env.proxyUrl});
// return moduleObject;
return {...moduleObject, ...initValue};
} catch (error) {
console.log(`Error in hipy.init :${filePath}`, error);
throw new Error(`Failed to initialize module:${error.message}`);
}
}
const home = async function (filePath, env, filter = 1) {
const moduleObject = await init(filePath, env);
return json2Object(await moduleObject.home(filter));
}
const homeVod = async function (filePath, env) {
const moduleObject = await init(filePath, env);
const homeVodResult = json2Object(await moduleObject.homeVod());
return homeVodResult && homeVodResult.list ? homeVodResult.list : homeVodResult;
}
const category = async function (filePath, env, tid, pg = 1, filter = 1, extend = {}) {
const moduleObject = await init(filePath, env);
return json2Object(await moduleObject.category(tid, pg, filter, extend));
}
const detail = async function (filePath, env, ids) {
const moduleObject = await init(filePath, env);
return json2Object(await moduleObject.detail(ids));
}
const search = async function (filePath, env, wd, quick = 0, pg = 1) {
const moduleObject = await init(filePath, env);
return json2Object(await moduleObject.search(wd, quick, pg));
}
const play = async function (filePath, env, flag, id, flags) {
const moduleObject = await init(filePath, env);
return json2Object(await moduleObject.play(flag, id, flags));
}
const proxy = async function (filePath, env, params) {
const moduleObject = await init(filePath, env);
return json2Object(await moduleObject.proxy(params));
}
const action = async function (filePath, env, action, value) {
const moduleObject = await init(filePath, env);
return json2Object(await moduleObject.action(action, value));
}
export default {
getRule,
init,
home,
homeVod,
category,
detail,
search,
play,
proxy,
action,
}