forked from hjdhnx/dr_py
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcms.py
1675 lines (1577 loc) · 71.7 KB
/
cms.py
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# File : cms.py
# Author: DaShenHan&道长-----先苦后甜,任凭晚风拂柳颜------
# Date : 2022/8/25
import json
# import bs4
import requests
import re
import math
import ujson
from utils.web import *
from utils.system import getHost
from utils.config import playerConfig
from utils.log import logger
from utils.encode import base64Encode, base64Decode, fetch, post, request, getCryptoJS, getPreJs, buildUrl, getHome, \
atob, btoa
from utils.encode import verifyCode, setDetail, join, urljoin2, parseText, requireCache, forceOrder, base64ToImage, \
encodeStr, decodeStr
from utils.encode import md5 as mmd5
from utils.safePython import safePython, safe_eval
from utils.parser import runPy, runJScode, JsObjectWrapper, PyJsObject, PyJsString
from utils.htmlParser import jsoup
from urllib.parse import urljoin, quote, unquote
from concurrent.futures import ThreadPoolExecutor # 引入线程池
from flask import url_for, redirect, render_template_string
from easydict import EasyDict as edict
from controllers.service import storage_service
def setItem(key, value):
lsg = storage_service()
if isinstance(key, PyJsString):
key = parseText(str(key))
if isinstance(value, PyJsString):
value = parseText(str(value))
return lsg.setItem(key, value)
def getItem(key, value=''):
lsg = storage_service()
if isinstance(key, PyJsString):
key = parseText(str(key))
if isinstance(value, PyJsString):
value = parseText(str(value))
return lsg.getItem(key, value)
def clearItem(key):
lsg = storage_service()
if isinstance(key, PyJsString):
key = parseText(str(key))
return lsg.clearItem(key)
def encodeUrl(url):
# return base64Encode(quote(url))
# return base64Encode(url)
# print(type(url))
if isinstance(url, PyJsString):
# obj = obj.to_dict()
url = parseText(str(url))
return quote(url)
def stringify(obj):
if isinstance(obj, PyJsObject):
# obj = obj.to_dict()
obj = parseText(str(obj))
return json.dumps(obj, separators=(',', ':'), ensure_ascii=False)
def requireObj(url):
if isinstance(url, PyJsString):
url = parseText(str(url))
return requireCache(url)
def md5(text):
if isinstance(text, PyJsString):
text = parseText(str(text))
return mmd5(text)
py_ctx = {
'requests': requests, 'print': print, 'base64Encode': base64Encode, 'base64Decode': base64Decode,
'log': logger.info, 'fetch': fetch, 'post': post, 'request': request, 'getCryptoJS': getCryptoJS,
'buildUrl': buildUrl, 'getHome': getHome, 'setDetail': setDetail, 'join': join, 'urljoin2': urljoin2,
'PC_UA': PC_UA, 'MOBILE_UA': MOBILE_UA, 'UC_UA': UC_UA, 'UA': UA, 'IOS_UA': IOS_UA,
'setItem': setItem, 'getItem': getItem, 'clearItem': clearItem, 'stringify': stringify, 'encodeUrl': encodeUrl,
'requireObj': requireObj, 'md5': md5, 'atob': atob, 'btoa': btoa, 'base64ToImage': base64ToImage,
'encodeStr': encodeStr,
'decodeStr': decodeStr
}
# print(getCryptoJS())
class CMS:
def __init__(self, rule, db=None, RuleClass=None, PlayParse=None, new_conf=None, ext=''):
if new_conf is None:
new_conf = {}
self.lsg = storage_service()
self.title = rule.get('title', '')
self.id = rule.get('id', self.title)
self.filter_url = rule.get('filter_url', '').replace('{{fl}}', '{{fl|safe}}') # python jinjia2禁用自动编码
cate_exclude = rule.get('cate_exclude', '')
tab_exclude = rule.get('tab_exclude', '')
self.lazy = rule.get('lazy', False)
# self.play_disable = new_conf.get('PLAY_DISABLE',False)
self.play_disable = self.lsg.getItem('PLAY_DISABLE', False)
self.retry_count = new_conf.get('RETRY_CNT', 3)
# self.lazy_mode = new_conf.get('LAZYPARSE_MODE')
self.lazy_mode = self.lsg.getItem('LAZYPARSE_MODE', 2)
self.ocr_api = new_conf.get('OCR_API')
# self.cate_exclude = new_conf.get('CATE_EXCLUDE','')
self.cate_exclude = self.lsg.getItem('CATE_EXCLUDE', '')
# self.tab_exclude = new_conf.get('TAB_EXCLUDE','')
self.tab_exclude = self.lsg.getItem('TAB_EXCLUDE', '')
if cate_exclude:
if not str(cate_exclude).startswith('|') and not str(self.cate_exclude).endswith('|'):
self.cate_exclude = self.cate_exclude + '|' + cate_exclude
else:
self.cate_exclude += cate_exclude
if tab_exclude:
if not str(tab_exclude).startswith('|') and not str(self.tab_exclude).endswith('|'):
self.tab_exclude = self.tab_exclude + '|' + tab_exclude
else:
self.tab_exclude += tab_exclude
# print(self.cate_exclude)
try:
self.vod = redirect(url_for('vod')).headers['Location']
except:
self.vod = '/vod'
# if not self.play_disable and self.lazy:
if not self.play_disable:
self.play_parse = rule.get('play_parse', False)
try:
play_url = getHost(self.lazy_mode)
except:
play_url = getHost(1, 5705)
# play_url = new_conf.get('PLAY_URL',getHost(2))
if not play_url.startswith('http'):
play_url = 'http://' + play_url
# print(play_url)
if self.play_parse:
# self.play_url = play_url + self.vod + '?play_url='
js0_password = self.lsg.getItem('JS0_PASSWORD')
# print(f'js0密码:{js0_password}')
js0_password = f'pwd={js0_password}&' if js0_password else ''
self.play_url = f'{play_url}{self.vod}?{js0_password}rule={self.id}&ext={ext}&play_url='
# logger.info(f'cms重定向链接:{self.play_url}')
else:
self.play_url = ''
else:
self.play_parse = False
self.play_url = ''
logger.info('播放免嗅地址: ' + self.play_url)
self.db = db
self.RuleClass = RuleClass
self.PlayParse = PlayParse
host = rule.get('host', '').rstrip('/')
host = unquote(host)
HOST = host
hostJs = rule.get('hostJs', '')
if hostJs:
try:
jsp = jsoup(HOST)
py_ctx.update({
'HOST': HOST,
'jsp': jsp,
'jq': jsp,
'TYPE': 'init',
})
ctx = py_ctx
jscode = getPreJs() + hostJs.strip().replace('js:', '', 1)
# print(jscode)
loader, _ = runJScode(jscode, ctx=ctx)
# print(loader.toString())
HOST = loader.eval('HOST')
# print(vods)
# 一般都是正常的str
if isinstance(HOST, PyJsString): # JsObjectWrapper
HOST = parseText(str(HOST))
host = HOST.rstrip('/')
print('host:', host)
except Exception as e:
logger.info(f'执行{hostJs}获取host发生错误:{e}')
timeout = rule.get('timeout', 5000)
homeUrl = rule.get('homeUrl', '/')
url = rule.get('url', '')
detailUrl = rule.get('detailUrl', '')
searchUrl = rule.get('searchUrl', '')
default_headers = getHeaders(host)
self_headers = rule.get('headers', {})
default_headers.update(self_headers)
headers = default_headers
cookie = self.getCookie()
# print(f'{self.title}cookie:{cookie}')
self.oheaders = self_headers
if cookie:
headers['cookie'] = cookie
self.oheaders['cookie'] = cookie
limit = rule.get('limit', 6)
encoding = rule.get('编码', 'utf-8')
search_encoding = rule.get('搜索编码', '')
self.limit = min(limit, 30)
keys = headers.keys()
for k in headers.keys():
if str(k).lower() == 'user-agent':
v = headers[k]
if v == 'MOBILE_UA':
headers[k] = MOBILE_UA
elif v == 'PC_UA':
headers[k] = PC_UA
elif v == 'UC_UA':
headers[k] = UC_UA
elif v == 'IOS_UA':
headers[k] = IOS_UA
elif str(k).lower() == 'cookie':
v = headers[k]
if v and str(v).startswith('http'):
try:
ck = requests.get(v, timeout=timeout, verify=False)
headers[k] = ck
except Exception as e:
logger.info(f'从{v}获取cookie发生错误:{e}')
pass
lower_keys = list(map(lambda x: x.lower(), keys))
if not 'user-agent' in lower_keys:
headers['User-Agent'] = UA
if not 'referer' in lower_keys:
headers['Referer'] = host
self.headers = headers
# print(headers)
self.host = host
self.homeUrl = urljoin(host, homeUrl) if host and homeUrl else homeUrl or host
if url.find('[') > -1 and url.find(']') > -1:
u1 = url.split('[')[0]
u2 = url.split('[')[1].split(']')[0]
self.url = urljoin(host, u1) + '[' + urljoin(host, u2) + ']' if host and url else url
else:
self.url = urljoin(host, url) if host and url else url
if searchUrl.find('[') > -1 and searchUrl.find(']') > -1 and '#' not in searchUrl:
u1 = searchUrl.split('[')[0]
u2 = searchUrl.split('[')[1].split(']')[0]
self.searchUrl = urljoin(host, u1) + '[' + urljoin(host, u2) + ']' if host and searchUrl else searchUrl
else:
self.searchUrl = urljoin(host, searchUrl) if host and searchUrl else searchUrl
self.detailUrl = urljoin(host, detailUrl) if host and detailUrl else detailUrl
self.class_name = rule.get('class_name', '')
self.class_url = rule.get('class_url', '')
self.class_parse = rule.get('class_parse', '')
self.filter_name = rule.get('filter_name', '')
self.filter_url = rule.get('filter_url', '')
self.filter_parse = rule.get('filter_parse', '')
self.double = rule.get('double', False)
self.一级 = rule.get('一级', '')
self.二级 = rule.get('二级', '')
self.二级访问前 = rule.get('二级访问前', '')
self.搜索 = rule.get('搜索', '')
self.推荐 = rule.get('推荐', '')
self.图片来源 = rule.get('图片来源', '')
self.encoding = encoding
self.search_encoding = search_encoding
self.timeout = round(int(timeout) / 1000, 2)
self.filter = rule.get('filter', [])
self.filter_def = rule.get('filter_def', {})
self.play_json = rule['play_json'] if 'play_json' in rule else []
self.pagecount = rule['pagecount'] if 'pagecount' in rule else {}
self.extend = rule.get('extend', [])
self.d = self.getObject()
def getName(self):
return self.title
def getObject(self):
o = edict({
'jsp': jsoup(self.url),
'getParse': self.getParse,
'saveParse': self.saveParse,
'oheaders': self.oheaders,
'headers': self.headers, # 通用免嗅需要
'encoding': self.encoding,
'name': self.title,
'timeout': self.timeout,
})
return o
def regexp(self, prule, text, pos=None):
ret = re.search(prule, text).groups()
if pos != None and isinstance(pos, int):
return ret[pos]
else:
return ret
def test(self, text, string):
searchObj = re.search(rf'{text}', string, re.M | re.I)
# print(searchObj)
# global vflag
if searchObj:
# vflag = searchObj.group()
pass
return searchObj
def blank(self):
result = {
'list': []
}
return result
def blank_vod(self):
return {
"vod_id": "id",
"vod_name": "片名",
"vod_pic": "", # 图片
"type_name": "剧情",
"vod_year": "年份",
"vod_area": "地区",
"vod_remarks": "更新信息",
"vod_actor": "主演",
"vod_director": "导演",
"vod_content": "简介"
}
def jsoup(self):
jsp = jsoup(self.url)
pdfh = jsp.pdfh
pdfa = jsp.pdfa
pd = jsp.pd
pjfh = jsp.pjfh
pjfa = jsp.pjfa
pj = jsp.pj
pq = jsp.pq
return pdfh, pdfa, pd, pq
def getClasses(self):
if not self.db:
msg = '未提供数据库连接'
print(msg)
return []
name = self.getName()
# self.db.metadata.clear()
# RuleClass = rule_classes.init(self.db)
res = self.db.session.query(self.RuleClass).filter(self.RuleClass.name == name).first()
# _logger.info('xxxxxx')
if res:
if not all([res.class_name, res.class_url]):
return []
cls = res.class_name.split('&')
cls2 = res.class_url.split('&')
classes = [{'type_name': cls[i], 'type_id': cls2[i]} for i in range(len(cls))]
# _logger.info(classes)
logger.info(f"{self.getName()}使用缓存分类:{classes}")
return classes
else:
return []
def getCookie(self):
name = self.getName()
if not self.db:
msg = f'{name}未提供数据库连接'
print(msg)
return False
res = self.db.session.query(self.RuleClass).filter(self.RuleClass.name == name).first()
if res:
return res.cookie or None
else:
return None
def saveCookie(self, cookie):
name = self.getName()
if not self.db:
msg = f'{name}未提供数据库连接'
print(msg)
return False
res = self.db.session.query(self.RuleClass).filter(self.RuleClass.name == name).first()
if res:
res.cookie = cookie
self.db.session.add(res)
else:
res = self.RuleClass(name=name, cookie=cookie)
self.db.session.add(res)
try:
self.db.session.commit()
logger.info(f'{name}已保存cookie:{cookie}')
except Exception as e:
return f'保存cookie发生了错误:{e}'
def saveClass(self, classes):
if not self.db:
msg = '未提供数据库连接'
print(msg)
return msg
name = self.getName()
class_name = '&'.join([cl['type_name'] for cl in classes])
class_url = '&'.join([cl['type_id'] for cl in classes])
# data = RuleClass.query.filter(RuleClass.name == '555影视').all()
# self.db.metadata.clear()
# RuleClass = rule_classes.init(self.db)
res = self.db.session.query(self.RuleClass).filter(self.RuleClass.name == name).first()
# print(res)
if res:
res.class_name = class_name
res.class_url = class_url
self.db.session.add(res)
msg = f'{self.getName()}修改成功:{res.id}'
else:
res = self.RuleClass(name=name, class_name=class_name, class_url=class_url)
self.db.session.add(res)
res = self.db.session.query(self.RuleClass).filter(self.RuleClass.name == name).first()
msg = f'{self.getName()}新增成功:{res.id}'
try:
self.db.session.commit()
logger.info(msg)
except Exception as e:
return f'发生了错误:{e}'
def getParse(self, play_url):
if not self.db:
msg = '未提供数据库连接'
print(msg)
return ''
name = self.getName()
# self.db.metadata.clear()
# RuleClass = rule_classes.init(self.db)
res = self.db.session.query(self.PlayParse).filter(self.PlayParse.play_url == play_url).first()
# _logger.info('xxxxxx')
if res:
real_url = res.real_url
logger.info(f"{name}使用缓存播放地址:{real_url}")
return real_url
else:
return ''
def dealJson(self, html):
try:
# res = re.search('.*?\{(.*)\}',html,re.M|re.I).groups()[0]
res = re.search('.*?\{(.*)\}', html, re.M | re.S).groups()[0]
html = '{' + res + '}'
return html
except:
return html
def checkHtml(self, r):
r.encoding = self.encoding
html = r.text
if html.find('?btwaf=') > -1:
btwaf = re.search('btwaf(.*?)"', html, re.M | re.I).groups()[0]
url = r.url.split('#')[0] + '?btwaf' + btwaf
# print(f'需要过宝塔验证:{url}')
cookies_dict = requests.utils.dict_from_cookiejar(r.cookies)
cookie_str = ';'.join([f'{k}={cookies_dict[k]}' for k in cookies_dict])
self.headers['cookie'] = cookie_str
r = requests.get(url, headers=self.headers, timeout=self.timeout, verify=False)
r.encoding = self.encoding
html = r.text
if html.find('?btwaf=') < 0:
self.saveCookie(cookie_str)
# print(html)
return html
def saveParse(self, play_url, real_url):
if not self.db:
msg = '未提供数据库连接'
print(msg)
return msg
name = self.getName()
# data = RuleClass.query.filter(RuleClass.name == '555影视').all()
# self.db.metadata.clear()
# RuleClass = rule_classes.init(self.db)
res = self.db.session.query(self.PlayParse).filter(self.PlayParse.play_url == play_url).first()
# print(res)
if res:
res.real_url = real_url
self.db.session.add(res)
msg = f'{name}服务端免嗅修改成功:{res.id}'
else:
res = self.PlayParse(play_url=play_url, real_url=real_url)
self.db.session.add(res)
res = self.db.session.query(self.PlayParse).filter(self.PlayParse.play_url == play_url).first()
msg = f'{name}服务端免嗅新增成功:{res.id}'
try:
self.db.session.commit()
logger.info(msg)
except Exception as e:
return f'{name}发生了错误:{e}'
def homeContent(self, fypage=1):
# yanaifei
# https://yanetflix.com/vodtype/dianying.html
t1 = time()
result = {}
classes = []
video_result = self.blank()
if self.class_url and self.class_name:
class_names = self.class_name.split('&')
class_urls = self.class_url.split('&')
cnt = min(len(class_urls), len(class_names))
for i in range(cnt):
classes.append({
'type_name': class_names[i],
'type_id': class_urls[i]
})
# print(self.url)
print(self.headers)
has_cache = False
# print(self.homeUrl)
if self.homeUrl.startswith('http'):
# print(self.class_parse)
try:
if self.class_parse:
t2 = time()
cache_classes = self.getClasses()
logger.info(f'{self.getName()}读取缓存耗时:{get_interval(t2)}毫秒')
if len(cache_classes) > 0:
classes = cache_classes
# print(cache_classes)
has_cache = True
# logger.info(f'是否有缓存分类:{has_cache}')
if has_cache and not self.推荐:
pass
else:
new_classes = []
r = requests.get(self.homeUrl, headers=self.headers, timeout=self.timeout, verify=False)
html = self.checkHtml(r)
# print(html)
# print(self.headers)
if self.class_parse and not has_cache:
p = self.class_parse.split(';')
# print(p[0])
# print(html)
jsp = jsoup(self.url)
pdfh = jsp.pdfh
pdfa = jsp.pdfa
pd = jsp.pd
items = pdfa(html, p[0])
# print(len(items))
# print(items)
for item in items:
title = pdfh(item, p[1])
# 过滤排除掉标题名称
if self.cate_exclude and jsp.test(self.cate_exclude, title):
continue
url = pd(item, p[2])
# print(url)
tag = url
if len(p) > 3 and p[3].strip():
try:
tag = self.regexp(p[3].strip(), url, 0)
except:
logger.info(f'分类匹配错误:{title}对应的链接{url}无法匹配{p[3]}')
continue
new_classes.append({
'type_name': title,
'type_id': tag
})
if len(new_classes) > 0:
classes.extend(new_classes)
self.saveClass(classes)
video_result = self.homeVideoContent(html, fypage)
except Exception as e:
logger.info(f'{self.getName()}主页发生错误:{e}')
classes = list(
filter(lambda x: not self.cate_exclude or not jsoup(self.url).test(self.cate_exclude, x['type_name']),
classes))
result['class'] = classes
if self.filter:
if isinstance(self.filter, dict):
result['filters'] = self.filter
else:
result['filters'] = playerConfig['filter']
result.update(video_result)
# print(result)
logger.info(f'{self.getName()}获取首页总耗时(包含读取缓存):{get_interval(t1)}毫秒')
return result
def homeVideoContent(self, html, fypage=1):
p = self.推荐
if not p:
return self.blank()
jsp = jsoup(self.homeUrl)
result = {}
videos = []
is_js = isinstance(p, str) and str(p).strip().startswith('js:') # 是js
if is_js:
headers['Referer'] = getHome(self.host)
py_ctx.update({
'input': self.homeUrl,
'HOST': self.host,
'TYPE': 'home', # 海阔js环境标志
'oheaders': self.d.oheaders,
'fetch_params': {'headers': self.headers, 'timeout': self.d.timeout, 'encoding': self.d.encoding},
'd': self.d,
'getParse': self.d.getParse,
'saveParse': self.d.saveParse,
'jsp': jsp, 'jq': jsp, 'setDetail': setDetail,
})
ctx = py_ctx
jscode = getPreJs() + p.strip().replace('js:', '', 1)
# print(jscode)
try:
loader, _ = runJScode(jscode, ctx=ctx)
# print(loader.toString())
vods = loader.eval('VODS')
# print(vods)
if isinstance(vods, JsObjectWrapper):
videos = vods.to_list()
except Exception as e:
logger.info(f'首页推荐执行js获取列表出错:{e}')
else:
if p == '*' and self.一级:
p = self.一级
self.double = False
logger.info(f'首页推荐继承一级: {p}')
p = p.strip().split(';') # 解析
if not self.double and len(p) < 5:
return self.blank()
if self.double and len(p) < 6:
return self.blank()
jsp = jsoup(self.homeUrl)
pp = self.一级.split(';')
def getPP(p, pn, pp, ppn):
try:
ps = pp[ppn] if p[pn] == '*' and len(pp) > ppn else p[pn]
return ps
except Exception as e:
return ''
p0 = getPP(p, 0, pp, 0)
is_json = str(p0).startswith('json:')
if is_json:
html = self.dealJson(html)
pdfh = jsp.pjfh if is_json else jsp.pdfh
pdfa = jsp.pjfa if is_json else jsp.pdfa
pd = jsp.pj if is_json else jsp.pd
# print(html)
try:
if self.double:
items = pdfa(html, p0.replace('json:', ''))
# print(p[0])
# print(items)
# print(len(items))
p1 = getPP(p, 1, pp, 0)
p2 = getPP(p, 2, pp, 1)
p3 = getPP(p, 3, pp, 2)
p4 = getPP(p, 4, pp, 3)
p5 = getPP(p, 5, pp, 4)
p6 = getPP(p, 6, pp, 5)
for item in items:
items2 = pdfa(item, p1)
# print(len(items2))
for item2 in items2:
try:
title = pdfh(item2, p2)
# print(title)
try:
img = pd(item2, p3)
except:
img = ''
try:
desc = pdfh(item2, p4)
except:
desc = ''
links = [pd(item2, _p5) if not self.detailUrl else pdfh(item2, _p5) for _p5 in
p5.split('+')]
vid = '$'.join(links)
if len(p) > 6 and p[6]:
content = pdfh(item2, p6)
else:
content = ''
if self.二级 == '*':
vid = vid + '@@' + title + '@@' + img
videos.append({
"vod_id": vid,
"vod_name": title,
"vod_pic": img,
"vod_remarks": desc,
"no_use": {
"vod_content": content,
"type_id": 1,
"type_name": "首页推荐",
},
})
except:
pass
else:
items = pdfa(html, p0.replace('json:', ''))
# print(items)
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)
for item in items:
try:
title = pdfh(item, p1)
try:
img = pd(item, p2)
except:
img = ''
try:
desc = pdfh(item, p3)
except:
desc = ''
# link = pd(item, p[4])
links = [pd(item, _p5) if not self.detailUrl else pdfh(item, _p5) for _p5 in p4.split('+')]
vid = '$'.join(links)
if len(p) > 5 and p[5]:
content = pdfh(item, p5)
else:
content = ''
if self.二级 == '*':
vid = vid + '@@' + title + '@@' + img
videos.append({
"vod_id": vid,
"vod_name": title,
"vod_pic": img,
"vod_remarks": desc,
"no_use": {
"vod_content": content,
"type_id": 1,
"type_name": "首页推荐",
},
})
except:
pass
# result['list'] = videos[min((fypage-1)*self.limit,len(videos)-1):min(fypage*self.limit,len(videos))]
except Exception as e:
logger.info(f'首页内容获取失败:{e}')
return self.blank()
if self.图片来源:
for video in videos:
if video.get('vod_pic', '') and str(video['vod_pic']).startswith('http'):
video['vod_pic'] = f"{video['vod_pic']}{self.图片来源}"
result['list'] = videos
# print(videos)
result['no_use'] = {
'code': 1,
'msg': '数据列表',
'page': fypage,
'pagecount': math.ceil(len(videos) / self.limit),
'limit': self.limit,
'total': len(videos),
'now_count': len(result['list']),
}
# print(result)
return result
def categoryContent(self, fyclass, fypage, fl=None):
"""
一级带分类的数据返回
:param fyclass: 分类标识
:param fypage: 页码
:param fl: 筛选
:return: cms一级数据
"""
if fl is None:
fl = {}
# print(f'fl:{fl}')
if self.filter_def and isinstance(self.filter_def, dict):
try:
if self.filter_def.get(fyclass) and isinstance(self.filter_def[fyclass], dict):
self_filter_def = self.filter_def[fyclass]
filter_def = ujson.loads(ujson.dumps(self_filter_def))
filter_def.update(fl)
fl = filter_def
except Exception as e:
print(f'合并不同分类对应的默认筛选出错:{e}')
# print(fl)
result = {}
# urlParams = ["", "", "", "", "", "", "", "", "", "", "", ""]
# urlParams = [""] * 12
# urlParams[0] = tid
# urlParams[8] = str(pg)
# for key in self.extend:
# urlParams[int(key)] = self.extend[key]
# params = '-'.join(urlParams)
# print(params)
# url = self.url + '/{0}.html'.format
t1 = time()
pg = str(fypage)
url = self.url.replace('fyclass', fyclass)
if fypage == 1 and self.test('[\[\]]', url):
url = url.split('[')[1].split(']')[0]
elif fypage > 1 and self.test('[\[\]]', url):
url = url.split('[')[0]
if self.filter_url:
if not 'fyfilter' in url: # 第一种情况,默认不写fyfilter关键字,视为直接拼接在链接后面当参数
if not url.endswith('&') and not self.filter_url.startswith('&'):
url += '&'
url += self.filter_url
else: # 第二种情况直接替换关键字为待拼接的结果后面渲染,适用于 ----fypage.html的情况
url = url.replace('fyfilter', self.filter_url)
# print(f'url渲染:{url}')
url = render_template_string(url, fl=fl)
# fl_url = render_template_string(self.filter_url,fl=fl)
# if not 'fyfilter' in url: # 第一种情况,默认不写fyfilter关键字,视为直接拼接在链接后面当参数
# if not url.endswith('&') and not fl_url.startswith('&'):
# url += '&'
# url += fl_url
# else: # 第二种情况直接替换关键字为渲染后的结果,适用于 ----fypage.html的情况
# url = url.replace('fyfilter',fl_url)
if url.find('fypage') > -1:
if '(' in url and ')' in url:
# url_rep = url[url.find('('):url.find(')')+1]
# cnt_page = url.split('(')[1].split(')')[0].replace('fypage',pg)
# print(url_rep)
url_rep = re.search('.*?\((.*)\)', url, re.M | re.S).groups()[0]
cnt_page = url_rep.replace('fypage', pg)
# print(url_rep)
# print(cnt_page)
cnt_ctx = {}
safe_eval(f'cnt_pg={cnt_page}', cnt_ctx)
# exec(f'cnt_pg={cnt_page}', cnt_ctx)
cnt_pg = str(cnt_ctx['cnt_pg']) if cnt_ctx.get('cnt_pg') else 1 # 计算表达式的结果
url = url.replace(url_rep, str(cnt_pg)).replace('(', '').replace(')', '')
# print(url)
else:
url = url.replace('fypage', pg)
# print(url)
logger.info(url)
p = self.一级
jsp = jsoup(self.url)
videos = []
is_js = isinstance(p, str) and str(p).startswith('js:') # 是js
if is_js:
headers['Referer'] = getHome(url)
py_ctx.update({
'input': url,
'TYPE': 'cate', # 海阔js环境标志
'oheaders': self.d.oheaders,
'fetch_params': {'headers': self.headers, 'timeout': self.d.timeout, 'encoding': self.d.encoding},
'd': self.d,
'MY_CATE': fyclass, # 分类id
'MY_FL': fl, # 筛选
'MY_PAGE': fypage, # 页数
'detailUrl': self.detailUrl or '', # 详情页链接
'getParse': self.d.getParse,
'saveParse': self.d.saveParse,
'jsp': jsp, 'jq': jsp, 'setDetail': setDetail,
})
ctx = py_ctx
# print(ctx)
jscode = getPreJs() + p.replace('js:', '', 1)
# print(jscode)
loader, _ = runJScode(jscode, ctx=ctx)
# print(loader.toString())
vods = loader.eval('VODS')
# print('vods:',vods)
if isinstance(vods, JsObjectWrapper):
videos = vods.to_list()
else:
p = p.split(';') # 解析
# print(len(p))
# print(p)
if len(p) < 5:
return self.blank()
is_json = str(p[0]).startswith('json:')
pdfh = jsp.pjfh if is_json else jsp.pdfh
pdfa = jsp.pjfa if is_json else jsp.pdfa
pd = jsp.pj if is_json else jsp.pd
# print(pdfh(r.text,'body a.module-poster-item.module-item:eq(1)&&Text'))
# print(pdfh(r.text,'body a.module-poster-item.module-item:eq(0)'))
# print(pdfh(r.text,'body a.module-poster-item.module-item:first'))
items = []
try:
r = requests.get(url, headers=self.headers, timeout=self.timeout, verify=False)
html = self.checkHtml(r)
print(self.headers)
# print(html)
if is_json:
html = self.dealJson(html)
html = json.loads(html)
# else:
# soup = bs4.BeautifulSoup(html, 'lxml')
# html = soup.prettify()
# print(html)
# with open('1.html',mode='w+',encoding='utf-8') as f:
# f.write(html)
items = pdfa(html, p[0].replace('json:', '', 1))
except:
pass
# print(items)
for item in items:
# print(item)
try:
title = pdfh(item, p[1])
img = pd(item, p[2])
desc = pdfh(item, p[3])
links = [pd(item, p4) if not self.detailUrl else pdfh(item, p4) for p4 in p[4].split('+')]
link = '$'.join(links)
content = '' if len(p) < 6 else pdfh(item, p[5])
# sid = self.regStr(sid, "/video/(\\S+).html")
vod_id = f'{fyclass}${link}' if self.detailUrl else link # 分类,播放链接
if self.二级 == '*':
vod_id = vod_id + '@@' + title + '@@' + img
videos.append({
"vod_id": vod_id,
"vod_name": title,
"vod_pic": img,
"vod_remarks": desc,
"vod_content": content,
})
except Exception as e:
print(f'发生了错误:{e}')
pass
if self.图片来源:
for video in videos:
if video.get('vod_pic', '') and str(video['vod_pic']).startswith('http'):
video['vod_pic'] = f"{video['vod_pic']}{self.图片来源}"
print('videos:', videos)
limit = 40
cnt = 9999 if len(videos) > 0 else 0
pagecount = 0
if self.pagecount and isinstance(self.pagecount, dict) and fyclass in self.pagecount:
print(f'fyclass:{fyclass},self.pagecount:{self.pagecount}')
pagecount = int(self.pagecount[fyclass])
result['list'] = videos
result['page'] = fypage
result['pagecount'] = pagecount or max(cnt, fypage)
result['limit'] = limit
result['total'] = cnt
# print(result)
# print(result['pagecount'])
logger.info(
f'{self.getName()}获取分类{fyclass}第{fypage}页耗时:{get_interval(t1)}毫秒,共计{round(len(str(result)) / 1000, 2)} kb')
nodata = {
'list': [{'vod_name': '无数据,防无限请求', 'vod_id': 'no_data', 'vod_remarks': '不要点,会崩的',
'vod_pic': 'https://ghproxy.net/https://raw.githubusercontent.com/hjdhnx/dr_py/main/404.jpg'}],
'total': 1, 'pagecount': 1, 'page': 1, 'limit': 1
}
# return result
return result if len(result['list']) > 0 else nodata
def 二级渲染(self, parse_str: 'str|dict', **kwargs):
# *args是不定长参数 列表
# ** args是不定长参数字典
p = parse_str # 二级传递解析表达式 js的obj json对象
detailUrl = kwargs.get('detailUrl', '') # 不定长字典传递的二级详情页vod_id详情处理数据
orId = kwargs.get('orId', '') # 不定长字典传递的二级详情页vod_id原始数据
url = kwargs.get('url', '') # 不定长字典传递的二级详情页链接智能拼接数据
vod = kwargs.get('vod', self.blank_vod()) # 最终要返回的二级详情页数据 默认空
html = kwargs.get('html', '') # 不定长字典传递的源码(如果不传才会在下面程序中去获取)
show_name = kwargs.get('show_name', '') # 是否显示来源(用于drpy区分)
jsp = kwargs.get('jsp', '') # jsp = jsoup(self.url) 传递的jsp解析
fyclass = kwargs.get('fyclass', '') # 二级传递的分类名称,可以得知进去的类别
play_url = self.play_url
vod_name = '片名'
vod_pic = ''
# print('二级url:',url)
if self.二级 == '*':
extra = orId.split('@@')
vod_name = extra[1] if len(extra) > 1 else vod_name
vod_pic = extra[2] if len(extra) > 2 else vod_pic
if self.play_json:
play_url = play_url.replace('&play_url=', '&type=json&play_url=')
if p == '*': # 解析表达式为*默认一级直接变播放
vod['vod_play_from'] = '道长在线'
vod['vod_remarks'] = detailUrl
vod['vod_actor'] = '没有二级,只有一级链接直接嗅探播放'
# vod['vod_content'] = url if not show_name else f'({self.id}) {url}'
vod['vod_content'] = url
vod['vod_id'] = orId
vod['vod_name'] = vod_name
vod['vod_pic'] = vod_pic
vod['vod_play_url'] = '嗅探播放$' + play_url + url.split('@@')[0]
elif not p or (not isinstance(p, dict) and not isinstance(p, str)) or (
isinstance(p, str) and not str(p).startswith('js:')):
pass
else:
is_json = p.get('is_json', False) if isinstance(p, dict) else False # 二级里加is_json参数
pdfh = jsp.pjfh if is_json else jsp.pdfh
pdfa = jsp.pjfa if is_json else jsp.pdfa
pd = jsp.pj if is_json else jsp.pd
pq = jsp.pq