-
Notifications
You must be signed in to change notification settings - Fork 283
Expand file tree
/
Copy pathdrpysParser.js
More file actions
1690 lines (1559 loc) · 59.1 KB
/
drpysParser.js
File metadata and controls
1690 lines (1559 loc) · 59.1 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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import vm from "vm";
import {
dealJson,
encodeStr,
forceOrder,
jinja,
nodata,
processImage,
SPECIAL_URL,
tellIsJx,
ungzip,
vodDeal,
} from "../libs_drpy/drpyCustom.js";
import {base64Decode, md5} from "../libs_drpy/crypto-util.js";
import {deepCopy, urljoin} from "../utils/utils.js";
// 注释:原hostHtmlCache已移除,统一使用pageRequestCache管理缓存
/**
* 页面请求缓存管理类
* 实现大小限制、FIFO策略和自动清理机制
*/
class PageRequestCache {
constructor(maxSize = 20, maxAge = 20000) {
this.cache = new Map();
this.accessOrder = []; // 记录访问顺序,用于FIFO
this.timers = new Map(); // 记录每个缓存项的定时器
this.maxSize = maxSize; // 最大缓存数量
this.maxAge = maxAge; // 最大存活时间(毫秒)
}
get(key) {
const item = this.cache.get(key);
if (item) {
// 更新访问顺序
this._updateAccessOrder(key);
return item.value;
}
return undefined;
}
set(key, value) {
// 如果已存在,先清理旧的定时器
if (this.cache.has(key)) {
this._clearTimer(key);
} else {
// 检查是否需要淘汰旧缓存
this._evictIfNeeded();
}
// 设置缓存项
const item = {
value,
timestamp: Date.now()
};
this.cache.set(key, item);
this._updateAccessOrder(key);
// 设置自动清理定时器
const timer = setTimeout(() => {
this.delete(key);
console.log(`[PageRequestCache] 自动清理过期缓存: ${key}`);
}, this.maxAge);
this.timers.set(key, timer);
console.log(`[PageRequestCache] 缓存已设置: ${key}, 当前缓存数量: ${this.cache.size}`);
}
delete(key) {
if (this.cache.has(key)) {
this.cache.delete(key);
this._clearTimer(key);
this._removeFromAccessOrder(key);
return true;
}
return false;
}
clear() {
// 清理所有定时器
for (const timer of this.timers.values()) {
clearTimeout(timer);
}
this.cache.clear();
this.accessOrder = [];
this.timers.clear();
console.log('[PageRequestCache] 已清理所有缓存');
}
has(key) {
return this.cache.has(key);
}
get size() {
return this.cache.size;
}
// 获取缓存统计信息
getStats() {
return {
size: this.cache.size,
maxSize: this.maxSize,
maxAge: this.maxAge,
keys: Array.from(this.cache.keys())
};
}
// 私有方法:更新访问顺序
_updateAccessOrder(key) {
this._removeFromAccessOrder(key);
this.accessOrder.push(key);
}
// 私有方法:从访问顺序中移除
_removeFromAccessOrder(key) {
const index = this.accessOrder.indexOf(key);
if (index > -1) {
this.accessOrder.splice(index, 1);
}
}
// 私有方法:清理定时器
_clearTimer(key) {
const timer = this.timers.get(key);
if (timer) {
clearTimeout(timer);
this.timers.delete(key);
}
}
// 私有方法:检查是否需要淘汰缓存
_evictIfNeeded() {
while (this.cache.size >= this.maxSize) {
// FIFO策略:移除最早访问的缓存项
const oldestKey = this.accessOrder[0];
if (oldestKey) {
console.log(`[PageRequestCache] FIFO淘汰缓存: ${oldestKey}`);
this.delete(oldestKey);
} else {
break;
}
}
}
// 迭代器支持
[Symbol.iterator]() {
return this.cache[Symbol.iterator]();
}
}
// 创建页面请求缓存实例
export const pageRequestCache = new PageRequestCache(20, 20000);
/**
* 创建解析器上下文对象
* @param {string} url - 解析的URL
* @param {Object} rule - 规则对象
* @param {Object} extraVars - 额外的变量
* @returns {Object} 解析器上下文
*/
function createParserContext(url, rule, extraVars = {}) {
const jsp = new jsoup(url);
return {
jsp,
pdfh: jsp.pdfh.bind(jsp),
pdfa: jsp.pdfa.bind(jsp),
pd: jsp.pd.bind(jsp),
pdfl: jsp.pdfl.bind(jsp),
pjfh: jsp.pjfh.bind(jsp),
pjfa: jsp.pjfa.bind(jsp),
pj: jsp.pj.bind(jsp),
MY_URL: url,
HOST: rule.host,
fetch_params: deepCopy(rule.rule_fetch_params),
...extraVars
};
}
/**
* 选择解析模式对应的解析函数
* @param {boolean} isJson - 是否为JSON模式
* @param {Object} context - 解析器上下文
* @returns {Object} 解析函数对象
*/
function selectParseMode(isJson, context) {
if (isJson) {
return {
$pdfa: context.pjfa,
$pdfh: context.pjfh,
$pd: context.pj
};
}
return {
$pdfa: context.pdfa,
$pdfh: context.pdfh,
$pd: context.pd
};
}
/**
* 缓存请求函数,专用于handleTemplateInheritance、commonClassParse、commonHomeListParse三个函数
* 这三个函数在同一次接口调用中共享缓存,host相同时复用HTML内容
* @param {Function} requestFunc - 请求函数
* @param {string} url - 请求URL
* @param {Object} options - 请求选项
* @param {string} cachePrefix - 缓存前缀,建议使用'host'
* @returns {Promise<string>} - 请求结果
*/
export async function cachedRequest(requestFunc, url, options = {}, cachePrefix = 'host') {
// 只为特定的三个函数提供缓存,使用host作为缓存键的主要部分
const cacheKey = `${cachePrefix}:${md5(url + JSON.stringify(options))}`;
// 检查缓存
let cached = pageRequestCache.get(cacheKey);
if (cached) {
log(`[cachedRequest] 使用缓存的页面内容: ${url}`);
return cached;
}
// 发起请求
log(`[cachedRequest] 首次请求页面: ${url}`);
try {
const result = await requestFunc(url, options);
if (result) {
// 缓存结果,使用新的PageRequestCache类(内置20秒自动清理)
pageRequestCache.set(cacheKey, result);
}
return result;
} catch (e) {
log(`[cachedRequest] 请求失败: ${url}, 错误: ${e.message}`);
return '';
}
}
/**
* 通用错误处理和日志记录函数
* @param {Function} operation - 要执行的操作函数
* @param {string} context - 上下文信息(用于日志)
* @param {*} defaultValue - 发生错误时的默认返回值
* @returns {Promise<*>} 操作结果或默认值
*/
async function safeExecute(operation, context, defaultValue = null) {
try {
return await operation();
} catch (e) {
log(`[${context}] 执行失败: ${e.message}`);
return defaultValue;
}
}
/**
* 安全解析HTML元素
* @param {Function} parseFunc - 解析函数
* @param {*} element - 要解析的元素
* @param {string} selector - 选择器
* @param {string} context - 上下文信息
* @param {string} defaultValue - 默认值
* @returns {string} 解析结果或默认值
*/
function safeParse(parseFunc, element, selector, context, defaultValue = '') {
try {
return parseFunc(element, selector).replace(/\n|\t/g, '').trim() || defaultValue;
} catch (e) {
log(`[${context}] 解析${selector}失败: ${e.message}`);
return defaultValue;
}
}
/**
* 安全解析URL(用于$pd函数)
* @param {Function} parseFunc - 解析函数($pd)
* @param {*} element - 要解析的元素
* @param {string} selector - 选择器
* @param {string} baseUrl - 基础URL
* @param {string} context - 上下文信息
* @param {string} defaultValue - 默认值
* @returns {string} 解析结果或默认值
*/
function safeParseUrl(parseFunc, element, selector, baseUrl, context, defaultValue = '') {
try {
return parseFunc(element, selector, baseUrl) || defaultValue;
} catch (e) {
log(`[${context}] 解析${selector}失败: ${e.message}`);
return defaultValue;
}
}
/**
* 通用视频对象后处理函数
* 统一处理图片和vodDeal调用
* @param {Object} vod - 视频对象
* @param {Object} moduleObject - 模块对象
* @param {Object} context - 上下文对象
* @returns {Promise<Object>} 处理后的视频对象
*/
async function processVodCommon(vod, moduleObject, context) {
// 处理图片
if (vod.vod_pic) {
try {
vod.vod_pic = await processImage(vod.vod_pic, moduleObject, context);
} catch (e) {
log(`[processVodCommon] 图片处理失败: ${e.message}`);
}
}
// 处理vodDeal
try {
vod = vodDeal(vod, moduleObject);
} catch (e) {
log(`[processVodCommon] vodDeal发生错误: ${e.message}`);
}
return vod;
}
/**
* 创建基础视频对象
* @param {string} orId - 原始ID
* @param {string} vod_name - 视频名称
* @param {string} vod_pic - 视频图片
* @returns {Object} 基础视频对象
*/
function createBaseVod(orId, vod_name = '片名', vod_pic = '') {
return {
vod_id: orId,
vod_name,
vod_pic,
type_name: '类型',
vod_year: '年份',
vod_area: '地区',
vod_remarks: '更新信息',
vod_actor: '主演',
vod_director: '导演',
vod_content: '简介',
};
}
// 构建视频对象的公共函数
async function buildVodObject(element, params, moduleObject, injectVars, context) {
const {p1, p2, p3, p4, p5} = params;
// 从context中获取解析函数
const {$pdfh, $pd, MY_URL} = context;
let vod_name = $pdfh(element, p1);
let vod_pic = '';
try {
vod_pic = $pd(element, p2);
} catch (e) {
}
let vod_remarks = '';
try {
vod_remarks = $pdfh(element, p3);
} catch (e) {
}
let links = [];
for (let _p5 of p4.split('+')) {
let link = !moduleObject.detailUrl ? $pd(element, _p5, MY_URL) : $pdfh(element, _p5);
links.push(link);
}
let vod_id = links.join('$');
let vod_content = '';
if (p5) {
try {
vod_content = $pdfh(element, p5);
} catch (e) {
}
}
if (moduleObject['二级'] === '*') {
vod_id = vod_id + '@@' + vod_name + '@@' + vod_pic;
}
if (vod_pic) {
vod_pic = await processImage(vod_pic, moduleObject, injectVars);
}
return {
'vod_id': vod_id,
'vod_name': vod_name,
'vod_pic': vod_pic,
'vod_remarks': vod_remarks,
'vod_content': vod_content,
};
}
export async function homeParse(rule) {
let url = rule.homeUrl;
if (typeof (rule.filter) === 'string' && rule.filter.trim().length > 0) {
try {
let filter_json = ungzip(rule.filter.trim());
// log(filter_json);
rule.filter = JSON.parse(filter_json);
} catch (e) {
log(`[homeParse] [${rule.title}] filter ungzip或格式化解密出错: ${e.message}`);
rule.filter = {};
}
}
let classes = [];
if (rule.class_name && rule.class_url) {
let names = rule.class_name.split('&');
let urls = rule.class_url.split('&');
let cnt = Math.min(names.length, urls.length);
for (let i = 0; i < cnt; i++) {
classes.push({
'type_id': urls[i],
'type_name': names[i],
'type_flag': rule['class_flag'],
});
}
}
const context = createParserContext(url, rule, {
TYPE: 'home',
input: url,
classes: classes,
filters: rule.filter,
cate_exclude: rule.cate_exclude,
home_flag: rule.home_flag,
});
return context;
}
export async function homeParseAfter(d, _type, hikerListCol, hikerClassListCol, hikerSkipEr, injectVars) {
if (!d) {
d = {};
}
d.type = _type || '影视';
if (hikerListCol) {
d.hikerListCol = hikerListCol;
}
if (hikerClassListCol) {
d.hikerClassListCol = hikerClassListCol;
}
// 跳过形式二级
if (hikerSkipEr) {
d.hikerSkipEr = hikerSkipEr;
}
const {
classes,
filters,
cate_exclude,
home_flag,
} = injectVars;
if (!Array.isArray(d.class)) {
d.class = classes;
}
if (!d.filters) {
d.filters = filters;
}
if (!d.list) {
d.list = [];
}
if (!d.type_flag && home_flag) {
d.type_flag = home_flag;
}
d.class = d.class.filter(it => !cate_exclude || !(new RegExp(cate_exclude).test(it.type_name)));
return d
}
export async function homeVodParse(rule) {
let url = rule.homeUrl;
return createParserContext(url, rule, {
TYPE: 'home',
input: url,
double: rule.double,
});
}
export async function cateParse(rule, tid, pg, filter, extend) {
log('[cateParse]', tid, pg, filter, extend);
let url = rule.url.replaceAll('fyclass', tid);
if (pg === 1 && url.includes('[') && url.includes(']')) {
url = url.split('[')[1].split(']')[0];
} else if (pg > 1 && url.includes('[') && url.includes(']')) {
url = url.split('[')[0];
}
if (rule.filter_def && typeof (rule.filter_def) === 'object') {
try {
if (Object.keys(rule.filter_def).length > 0 && rule.filter_def.hasOwnProperty(tid)) {
let self_fl_def = rule.filter_def[tid];
if (self_fl_def && typeof (self_fl_def) === 'object') {
let k = [Object.keys(self_fl_def)][0]
k.forEach(k => {
if (!extend.hasOwnProperty(k)) {
extend[k] = self_fl_def[k];
}
})
}
}
} catch (e) {
log(`[cateParse] 合并不同分类对应的默认筛选出错:${e.message}`);
}
}
if (rule.filter_url) {
if (!/fyfilter/.test(url)) {
if (!url.endsWith('&') && !rule.filter_url.startsWith('&')) {
url += '&'
}
url += rule.filter_url;
} else {
url = url.replace('fyfilter', rule.filter_url);
}
url = url.replaceAll('fyclass', tid);
let fl = filter ? extend : {};
if (rule.filter_def && typeof (rule.filter_def) === 'object') {
try {
if (Object.keys(rule.filter_def).length > 0 && rule.filter_def.hasOwnProperty(tid)) {
let self_fl_def = rule.filter_def[tid];
if (self_fl_def && typeof (self_fl_def) === 'object') {
let fl_def = deepCopy(self_fl_def);
fl = Object.assign(fl_def, fl);
}
}
} catch (e) {
log(`[cateParse] 合并不同分类对应的默认筛选出错:${e.message}`);
}
}
let new_url;
new_url = jinja.render(url, {fl: fl, fyclass: tid});
url = new_url;
}
if (/fypage/.test(url)) {
if (url.includes('(') && url.includes(')')) {
let url_rep = url.match(/.*?\((.*)\)/)[1];
let cnt_page = url_rep.replaceAll('fypage', pg);
let cnt_pg = eval(cnt_page);
url = url.replaceAll(url_rep, cnt_pg).replaceAll('(', '').replaceAll(')', '');
} else {
url = url.replaceAll('fypage', pg);
}
}
return createParserContext(url, rule, {
MY_CATE: tid,
MY_FL: extend,
TYPE: 'cate',
input: url,
MY_PAGE: pg,
});
}
export async function cateParseAfter(rule, d, pg) {
return d.length < 1 ? nodata : {
'page': parseInt(pg),
'pagecount': 9999,
'limit': Number(rule.limit) || 20,
'total': 999999,
'list': d,
}
}
export async function detailParse(rule, ids) {
let vid = ids[0].toString();
let orId = vid;
let fyclass = '';
log('[detailParse] orId:' + orId);
if (vid.indexOf('$') > -1) {
let tmp = vid.split('$');
fyclass = tmp[0];
vid = tmp[1];
}
let detailUrl = vid.split('@@')[0];
let url;
if (!detailUrl.startsWith('http') && !detailUrl.includes('/')) {
url = rule.detailUrl.replaceAll('fyid', detailUrl).replaceAll('fyclass', fyclass);
} else if (detailUrl.includes('/')) {
url = urljoin(rule.homeUrl, detailUrl);
} else {
url = detailUrl
}
return createParserContext(url, rule, {
TYPE: 'detail',
input: url,
vid: vid,
orId: orId,
fyclass: fyclass,
detailUrl: detailUrl,
});
}
export async function detailParseAfter(vod) {
return {
list: [vod]
}
}
export async function searchParse(rule, wd, quick, pg) {
if (rule.search_encoding) {
if (rule.search_encoding.toLowerCase() !== 'utf-8') {
// 按搜索编码进行编码
wd = encodeStr(wd, rule.search_encoding);
}
} else if (rule.encoding && rule.encoding.toLowerCase() !== 'utf-8') {
// 按全局编码进行编码
wd = encodeStr(wd, rule.encoding);
}
if (!rule.searchUrl) {
return
}
if (rule.searchNoPage && Number(pg) > 1) {
// 关闭搜索分页
return '{}'
}
let url = rule.searchUrl.replaceAll('**', wd);
if (pg === 1 && url.includes('[') && url.includes(']') && !url.includes('#')) {
url = url.split('[')[1].split(']')[0];
} else if (pg > 1 && url.includes('[') && url.includes(']') && !url.includes('#')) {
url = url.split('[')[0];
}
if (/fypage/.test(url)) {
if (url.includes('(') && url.includes(')')) {
let url_rep = url.match(/.*?\((.*)\)/)[1];
let cnt_page = url_rep.replaceAll('fypage', pg);
let cnt_pg = eval(cnt_page);
url = url.replaceAll(url_rep, cnt_pg).replaceAll('(', '').replaceAll(')', '');
} else {
url = url.replaceAll('fypage', pg);
}
}
return createParserContext(url, rule, {
TYPE: 'search',
MY_PAGE: pg,
KEY: wd,
input: url,
detailUrl: rule.detailUrl || '',
});
}
export async function searchParseAfter(rule, d, pg) {
return {
'page': parseInt(pg),
'pagecount': 9999,
'limit': Number(rule.limit) || 20,
'total': 999999,
'list': d,
}
}
export async function playParse(rule, flag, id, flags) {
let url = id;
if (!/http/.test(url)) {
try {
url = base64Decode(url);
log('[playParse] id is base64 data');
} catch (e) {
}
}
url = decodeURIComponent(url);
if (!/^http/.test(url)) {
url = id;
}
if (id !== url) {
log(`[playParse] ${id} => ${url}`);
} else {
log(`[playParse] ${url}`);
}
return createParserContext(url, rule, {
TYPE: 'play',
MY_FLAG: flag,
flag: flag,
input: url,
});
}
export async function playParseAfter(rule, obj, playUrl, flag) {
let common_play = {
parse: SPECIAL_URL.test(playUrl) || /^(push:)/.test(playUrl) ? 0 : 1,
url: playUrl,
flag: flag,
jx: tellIsJx(playUrl)
};
let lazy_play;
const is_lazy_function = rule.play_parse && rule.lazy && typeof (rule.lazy) === 'function';
const is_lazy_function_str = rule.play_parse && rule.lazy && typeof (rule.lazy) === 'string' && rule.lazy.startsWith('js:');
if (!rule.play_parse || !rule.lazy) {
lazy_play = common_play;
} else if (is_lazy_function || is_lazy_function_str) {
try {
lazy_play = typeof (obj) === 'object' ? obj : {
parse: SPECIAL_URL.test(obj) || /^(push:)/.test(obj) ? 0 : 1,
jx: tellIsJx(obj),
url: obj
};
} catch (e) {
log(`[playParseAfter] js免嗅错误:${e.message}`);
lazy_play = common_play;
}
} else {
lazy_play = common_play;
}
if (Array.isArray(rule.play_json) && rule.play_json.length > 0) { // 数组情况判断长度大于0
let web_url = lazy_play.url;
for (let pjson of rule.play_json) {
if (pjson.re && (pjson.re === '*' || web_url.match(new RegExp(pjson.re)))) {
if (pjson.json && typeof (pjson.json) === 'object') {
let base_json = pjson.json;
lazy_play = Object.assign(lazy_play, base_json);
break;
}
}
}
} else if (rule.play_json && !Array.isArray(rule.play_json)) { // 其他情况 非[] 判断true/false
let base_json = {
jx: 1,
parse: 1,
};
lazy_play = Object.assign(lazy_play, base_json);
} else if (!rule.play_json) { // 不解析传0
let base_json = {
jx: 0,
parse: 1,
};
lazy_play = Object.assign(lazy_play, base_json);
}
return lazy_play
}
export async function proxyParse(rule, params) {
// log('proxyParse:', params);
return {
TYPE: 'proxy',
input: params.url || '',
MY_URL: params.url || '',
}
}
/**
* 通用分类解析函数
* @param moduleObject
* @param method
* @param injectVars
* @param args
* @returns {Promise<*>}
*/
export async function commonClassParse(moduleObject, method, injectVars, args) {
// class_parse字符串p
let p = moduleObject[method].trim();
let cate_exclude = moduleObject['cate_exclude'].trim();
const tmpFunction = async function () {
const {input, MY_URL, pdfa, pdfh, pd, pjfa, pjfh, pj} = this;
let classes = [];
// 处理class_parse字符串解析
p = p.split(';');
let p0 = p[0];
let is_json = p0.startsWith('json:');
p0 = p0.replace(/^(jsp:|json:|jq:)/, '');
// 通过沙箱执行cachedRequest函数,保证同一会话缓存共享
let html = await executeSandboxFunction('cachedRequest', [sandboxVar('request'), sandboxString(input), {}, sandboxString('host')], moduleObject.context, '获取HTML异常', '');
if (html) {
if (is_json) {
html = dealJson(html);
}
const {$pdfa, $pdfh, $pd} = selectParseMode(is_json, this);
if (is_json) {
try {
let list = $pdfa(html, p0);
if (list && list.length > 0) {
classes = list;
}
} catch (e) {
log(`[commonClassParse] json分类解析失败:${e.message}`);
}
} else if (p.length >= 3) { // 可以不写正则
try {
let list = $pdfa(html, p0);
if (list && list.length > 0) {
for (const it of list) {
try {
//log('[commonClassParse] it:', it);
let name = $pdfh(it, p[1]);
if (cate_exclude && (new RegExp(cate_exclude).test(name))) {
continue;
}
let url = $pd(it, p[2]);
if (p.length > 3 && p[3]) {
let exp = new RegExp(p[3]);
let match = url.match(exp);
if (match && match[1]) {
url = match[1];
}
}
if (name.trim()) {
classes.push({
'type_id': url.trim(),
'type_name': name.trim()
});
}
} catch (e) {
log(`[commonClassParse] 分类列表解析元素失败:${e.message}`);
}
}
}
} catch (e) {
log(`[commonClassParse] 分类列表解析失败:${e.message}`);
}
}
}
return {class: classes};
};
return await invokeWithInjectVars(moduleObject, tmpFunction, injectVars, args);
}
/**
* 通用推荐字符串解析函数
* @param moduleObject
* @param method
* @param injectVars
* @param args
* @returns {Promise<*>}
*/
export async function commonHomeListParse(moduleObject, method, injectVars, args) {
// 推荐字符串p
let p = moduleObject[method] === '*' && moduleObject['一级'] ? moduleObject['一级'] : moduleObject[method];
// 一级是函数直接调用函数
if (typeof p === 'function') {
// log('推荐继承一级函数');
return await invokeWithInjectVars(moduleObject, p, injectVars, args);
}
// 推荐完全和一级相同的话,双重定位为false
if (moduleObject[method] === '*') {
moduleObject['double'] = false;
}
p = p.trim();
let pp = typeof moduleObject['一级'] === 'string' ? moduleObject['一级'].split(';') : [];
const is_double = moduleObject.double;
const tmpFunction = async function () {
const {input, MY_URL, pdfa, pdfh, pd, pjfa, pjfh, pj} = this;
const d = [];
// 使用公用函数初始化解析配置
const config = initCommonParseConfig(p, pp, MY_URL, moduleObject);
const {p: parsedP, p0, is_json, parseParams} = config;
if ((!is_double && parsedP.length < 5) || (is_double && parsedP.length < 6)) {
return d
}
// 使用公用函数获取HTML
let html = await getCommonHtml(MY_URL, moduleObject, 'cachedRequest');
if (html) {
// 重新赋值p为解析后的数组
p = parsedP;
if (is_double) {
// 双重解析逻辑
if (is_json) {
html = dealJson(html);
}
const {$pdfa, $pdfh, $pd} = selectParseMode(is_json, this);
let list = $pdfa(html, p0);
const parseContext = {$pdfa, $pdfh, $pd, MY_URL};
let p1 = getPP(p, 1, pp, 0);
let p2 = getPP(p, 2, pp, 1);
let p3 = getPP(p, 3, pp, 2);
let p4 = getPP(p, 4, pp, 3);
let p5 = getPP(p, 5, pp, 4);
let p6 = getPP(p, 6, pp, 5);
for (const it of list) {
let list2 = $pdfa(it, p1);
for (let it2 of list2) {
const params = {
p1: p2,
p2: p3,
p3: p4,
p4: p5,
p5: p.length > 6 && p[6] ? p6 : ''
};
const vod = await buildVodObject(it2, params, moduleObject, injectVars, parseContext);
d.push(vod);
}
}
} else {
// 使用通用列表解析函数
const result = await parseCommonList(html, config, this, moduleObject, injectVars);
d.push(...result);
}
}
return d
};
return await invokeWithInjectVars(moduleObject, tmpFunction, injectVars, args);
}
/**
* 通用解析初始化逻辑
* @param {string} p - 解析字符串
* @param {Array} pp - 一级解析分割列表
* @param {string} MY_URL - 当前URL
* @param {Object} moduleObject - 模块对象
* @returns {Object} 包含解析配置的对象
*/
function initCommonParseConfig(p, pp, MY_URL, moduleObject) {
p = p.split(';');
let p0 = getPP(p, 0, pp, 0);
let is_json = p0.startsWith('json:');
p0 = p0.replace(/^(jsp:|json:|jq:)/, '');
return {
p,
p0,
is_json,
parseParams: {
p1: getPP(p, 1, pp, 1),
p2: getPP(p, 2, pp, 2),
p3: getPP(p, 3, pp, 3),
p4: getPP(p, 4, pp, 4),
p5: getPP(p, 5, pp, 5)
}
};
}
/**
* 通用HTML获取逻辑
* @param {string} url - 请求URL
* @param {Object} moduleObject - 模块对象
* @param {string} method - 请求方法类型
* @returns {Promise<string>} HTML内容
*/
async function getCommonHtml(url, moduleObject, method = 'get') {
if (method === 'cachedRequest') {
return await executeSandboxFunction('cachedRequest', [sandboxVar('request'), sandboxString(url), {}, sandboxString('host')], moduleObject.context, '获取HTML异常', '');
} else if (method === 'request') {
return await executeSandboxFunction('request', [sandboxString(url), {}], moduleObject.context, '获取HTML异常', '');
} else {
return await executeSandboxFunction('getHtml', [sandboxString(url)], moduleObject.context, '获取HTML异常', '');
}
}
/**
* 通用列表解析逻辑
* @param {string} html - HTML内容
* @param {Object} config - 解析配置
* @param {Object} context - 解析上下文
* @param {Object} moduleObject - 模块对象
* @param {Object} injectVars - 注入变量
* @returns {Array} 解析结果列表
*/
async function parseCommonList(html, config, context, moduleObject, injectVars) {
const {p0, is_json, parseParams} = config;
const d = [];
if (is_json) {
html = dealJson(html);
}
const {$pdfa, $pdfh, $pd} = selectParseMode(is_json, context);
let list = $pdfa(html, p0);
const parseContext = {$pdfa, $pdfh, $pd, MY_URL: context.MY_URL};
for (const it of list) {
const vod = await buildVodObject(it, parseParams, moduleObject, injectVars, parseContext);
d.push(vod);
}
return d;
}
/**
* 推荐和搜索单字段继承一级
* @param p 推荐或搜索的解析分割;列表
* @param pn 自身列表序号
* @param pp 一级解析分割;列表
* @param ppn 继承一级序号
* @returns {*}
*/
function getPP(p, pn, pp, ppn) {
try {
return p[pn] === '*' && pp.length > ppn ? pp[ppn] : p[pn]
} catch (e) {
return ''
}
}
/**
* 通用一级字符串解析函数
* @param moduleObject
* @param method
* @param injectVars
* @param args
* @returns {Promise<*>}
*/
export async function commonCategoryListParse(moduleObject, method, injectVars, args) {
// 一级字符串p
let p = moduleObject[method].trim();
const tmpFunction = async function () {
const {input, MY_URL, MY_CATE, pdfa, pdfh, pd, pjfa, pjfh, pj} = this;
const d = [];