cms.py 66.5 KB
Newer Older
H
hjdhnx 已提交
1 2 3 4 5
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# File  : cms.py
# Author: DaShenHan&道长-----先苦后甜,任凭晚风拂柳颜------
# Date  : 2022/8/25
H
hjdhnx 已提交
6
import json
H
hjdhnx 已提交
7
# import bs4
H
hjdhnx 已提交
8 9 10
import requests
import re
import math
H
hjdhnx 已提交
11 12
import ujson

H
hjdhnx 已提交
13 14 15 16
from utils.web import *
from utils.system import getHost
from utils.config import playerConfig
from utils.log import logger
H
hjdhnx 已提交
17
from utils.encode import base64Encode,base64Decode,fetch,post,request,getCryptoJS,getPreJs,buildUrl,getHome
H
hjdhnx 已提交
18
from utils.encode import verifyCode,setDetail,join,urljoin2,parseText,requireCache,forceOrder
H
hjdhnx 已提交
19
from utils.encode import md5 as mmd5
H
hjdhnx 已提交
20
from utils.safePython import safePython
H
hjdhnx 已提交
21
from utils.parser import runPy,runJScode,JsObjectWrapper,PyJsObject,PyJsString
H
hjdhnx 已提交
22
from utils.htmlParser import jsoup
H
hjdhnx 已提交
23
from urllib.parse import urljoin,quote,unquote
H
hjdhnx 已提交
24
from concurrent.futures import ThreadPoolExecutor  # 引入线程池
H
hjdhnx 已提交
25
from flask import url_for,redirect,render_template_string
H
hjdhnx 已提交
26
from easydict import EasyDict as edict
H
hjdhnx 已提交
27
from controllers.service import storage_service
H
hjdhnx 已提交
28

H
hjdhnx 已提交
29 30
def setItem(key,value):
    lsg = storage_service()
H
hjdhnx 已提交
31 32 33 34
    if isinstance(key,PyJsString):
        key = parseText(str(key))
    if isinstance(value,PyJsString):
        value = parseText(str(value))
H
hjdhnx 已提交
35 36 37 38
    return lsg.setItem(key,value)

def getItem(key,value=''):
    lsg = storage_service()
H
hjdhnx 已提交
39 40 41 42
    if isinstance(key,PyJsString):
        key = parseText(str(key))
    if isinstance(value,PyJsString):
        value = parseText(str(value))
H
hjdhnx 已提交
43 44 45 46
    return lsg.getItem(key,value)

def clearItem(key):
    lsg = storage_service()
H
hjdhnx 已提交
47 48
    if isinstance(key,PyJsString):
        key = parseText(str(key))
H
hjdhnx 已提交
49 50
    return lsg.clearItem(key)

H
hjdhnx 已提交
51 52 53
def encodeUrl(url):
    # return base64Encode(quote(url))
    # return base64Encode(url)
H
hjdhnx 已提交
54 55 56 57
    # print(type(url))
    if isinstance(url,PyJsString):
        # obj = obj.to_dict()
        url = parseText(str(url))
H
hjdhnx 已提交
58 59
    return quote(url)

H
hjdhnx 已提交
60 61 62 63 64 65
def stringify(obj):
    if isinstance(obj,PyJsObject):
        # obj = obj.to_dict()
        obj = parseText(str(obj))
    return json.dumps(obj, separators=(',', ':'), ensure_ascii=False)

H
hjdhnx 已提交
66 67 68 69 70 71 72 73 74 75
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)

H
hjdhnx 已提交
76
py_ctx = {
H
hjdhnx 已提交
77
'requests':requests,'print':print,'base64Encode':base64Encode,'base64Decode':base64Decode,
H
hjdhnx 已提交
78
'log':logger.info,'fetch':fetch,'post':post,'request':request,'getCryptoJS':getCryptoJS,
H
hjdhnx 已提交
79
'buildUrl':buildUrl,'getHome':getHome,'setDetail':setDetail,'join':join,'urljoin2':urljoin2,
H
hjdhnx 已提交
80
'PC_UA':PC_UA,'MOBILE_UA':MOBILE_UA,'UC_UA':UC_UA,'UA':UA,'IOS_UA':IOS_UA,
H
hjdhnx 已提交
81 82
'setItem':setItem,'getItem':getItem,'clearItem':clearItem,'stringify':stringify,'encodeUrl':encodeUrl,
'requireObj':requireObj,'md5':md5
H
hjdhnx 已提交
83 84 85 86
}
# print(getCryptoJS())

class CMS:
H
hjdhnx 已提交
87
    def __init__(self, rule, db=None, RuleClass=None, PlayParse=None,new_conf=None,ext=''):
H
hjdhnx 已提交
88 89
        if new_conf is None:
            new_conf = {}
H
hjdhnx 已提交
90
        self.lsg = storage_service()
H
hjdhnx 已提交
91 92
        self.title = rule.get('title', '')
        self.id = rule.get('id', self.title)
H
hjdhnx 已提交
93
        self.filter_url = rule.get('filter_url', '').replace('{{fl}}','{{fl|safe}}') # python jinjia2禁用自动编码
H
hjdhnx 已提交
94
        cate_exclude  = rule.get('cate_exclude','')
H
hjdhnx 已提交
95
        tab_exclude  = rule.get('tab_exclude','')
H
hjdhnx 已提交
96
        self.lazy = rule.get('lazy', False)
H
hjdhnx 已提交
97 98
        # self.play_disable = new_conf.get('PLAY_DISABLE',False)
        self.play_disable = self.lsg.getItem('PLAY_DISABLE',False)
H
hjdhnx 已提交
99
        self.retry_count = new_conf.get('RETRY_CNT',3)
H
hjdhnx 已提交
100
        # self.lazy_mode = new_conf.get('LAZYPARSE_MODE')
H
优化  
hjdhnx 已提交
101
        self.lazy_mode = self.lsg.getItem('LAZYPARSE_MODE',2)
H
hjdhnx 已提交
102
        self.ocr_api = new_conf.get('OCR_API')
H
hjdhnx 已提交
103 104 105 106
        # 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','')
H
hjdhnx 已提交
107 108 109 110 111
        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
H
hjdhnx 已提交
112 113 114 115 116
        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
H
hjdhnx 已提交
117
        # print(self.cate_exclude)
H
hjdhnx 已提交
118 119 120 121 122 123 124 125 126 127 128 129 130 131
        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
H
优化  
hjdhnx 已提交
132
            # print(play_url)
H
hjdhnx 已提交
133 134
            if self.play_parse:
                # self.play_url = play_url + self.vod + '?play_url='
H
hjdhnx 已提交
135 136 137 138
                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='
H
hjdhnx 已提交
139 140 141 142 143 144
                # logger.info(f'cms重定向链接:{self.play_url}')
            else:
                self.play_url = ''
        else:
            self.play_parse = False
            self.play_url = ''
H
优化  
hjdhnx 已提交
145
        logger.info('播放免嗅地址: '+self.play_url)
H
hjdhnx 已提交
146 147 148 149 150

        self.db = db
        self.RuleClass = RuleClass
        self.PlayParse = PlayParse
        host = rule.get('host','').rstrip('/')
H
hjdhnx 已提交
151
        host = unquote(host)
H
hjdhnx 已提交
152 153 154 155 156 157 158 159 160 161 162
        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}')
H
hjdhnx 已提交
163
        self.oheaders = self_headers
H
hjdhnx 已提交
164 165
        if cookie:
            headers['cookie'] = cookie
H
hjdhnx 已提交
166
            self.oheaders['cookie'] = cookie
H
hjdhnx 已提交
167 168 169 170 171 172 173 174 175 176 177 178 179
        limit = rule.get('limit',6)
        encoding = rule.get('编码', 'utf-8')
        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
H
hjdhnx 已提交
180 181
                elif v == 'IOS_UA':
                    headers[k] = IOS_UA
H
hjdhnx 已提交
182 183 184 185 186 187
        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
H
hjdhnx 已提交
188
        # print(headers)
H
hjdhnx 已提交
189
        self.host = host
H
hjdhnx 已提交
190
        self.homeUrl = urljoin(host,homeUrl) if host and homeUrl else homeUrl or host
H
hjdhnx 已提交
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
        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

        self.detailUrl = urljoin(host,detailUrl) if host and detailUrl else detailUrl
        self.searchUrl = urljoin(host,searchUrl) if host and searchUrl else searchUrl
        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('推荐','')
H
hjdhnx 已提交
211
        self.图片来源 = rule.get('图片来源','')
H
hjdhnx 已提交
212 213 214
        self.encoding = encoding
        self.timeout = round(int(timeout)/1000,2)
        self.filter = rule.get('filter',[])
H
hjdhnx 已提交
215
        self.filter_def = rule.get('filter_def',{})
H
hjdhnx 已提交
216
        self.play_json = rule['play_json'] if 'play_json' in rule else []
H
hjdhnx 已提交
217
        self.pagecount = rule['pagecount'] if 'pagecount' in rule else {}
H
hjdhnx 已提交
218 219 220 221 222 223 224 225 226 227 228
        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,
H
hjdhnx 已提交
229
            'oheaders':self.oheaders,
230
            'headers':self.headers, # 通用免嗅需要
H
hjdhnx 已提交
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
            '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 {
261 262 263 264 265 266 267 268 269 270
            "vod_id": "id",
            "vod_name": "片名",
            "vod_pic": "",# 图片
            "type_name": "剧情",
            "vod_year": "年份",
            "vod_area": "地区",
            "vod_remarks": "更新信息",
            "vod_actor": "主演",
            "vod_director": "导演",
            "vod_content": "简介"
H
hjdhnx 已提交
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
        }

    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 ''

H
hjdhnx 已提交
385 386
    def dealJson(self,html):
        try:
H
hjdhnx 已提交
387 388
            # res = re.search('.*?\{(.*)\}',html,re.M|re.I).groups()[0]
            res = re.search('.*?\{(.*)\}',html,re.M|re.S).groups()[0]
H
hjdhnx 已提交
389 390 391 392 393
            html = '{' + res + '}'
            return html
        except:
            return html

H
hjdhnx 已提交
394 395 396 397 398 399 400 401 402 403
    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
H
hjdhnx 已提交
404
            r = requests.get(url, headers=self.headers, timeout=self.timeout,verify=False)
H
hjdhnx 已提交
405 406 407 408 409 410 411 412
            r.encoding = self.encoding
            html = r.text
            if html.find('?btwaf=') < 0:
                self.saveCookie(cookie_str)

        # print(html)
        return html

H
hjdhnx 已提交
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
    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
H
hjdhnx 已提交
461
        # print(self.homeUrl)
H
hjdhnx 已提交
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
        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 = []
H
hjdhnx 已提交
478
                    r = requests.get(self.homeUrl, headers=self.headers, timeout=self.timeout,verify=False)
H
hjdhnx 已提交
479
                    html = self.checkHtml(r)
H
hjdhnx 已提交
480 481 482 483
                    # print(html)
                    # print(self.headers)
                    if self.class_parse and not has_cache:
                        p = self.class_parse.split(';')
H
hjdhnx 已提交
484 485
                        # print(p[0])
                        # print(html)
H
hjdhnx 已提交
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501
                        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():
H
hjdhnx 已提交
502 503 504 505 506
                                try:
                                    tag = self.regexp(p[3].strip(),url,0)
                                except:
                                    logger.info(f'分类匹配错误:{title}对应的链接{url}无法匹配{p[3]}')
                                    continue
H
hjdhnx 已提交
507 508 509 510 511 512 513 514 515 516
                            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}')
517
        classes = list(filter(lambda x:not self.cate_exclude or not jsoup(self.url).test(self.cate_exclude, x['type_name']),classes))
H
hjdhnx 已提交
518 519
        result['class'] = classes
        if self.filter:
H
hjdhnx 已提交
520 521 522 523
            if isinstance(self.filter,dict):
                result['filters'] = self.filter
            else:
                result['filters'] = playerConfig['filter']
H
hjdhnx 已提交
524 525 526 527 528 529
        result.update(video_result)
        # print(result)
        logger.info(f'{self.getName()}获取首页总耗时(包含读取缓存):{get_interval(t1)}毫秒')
        return result

    def homeVideoContent(self,html,fypage=1):
H
hjdhnx 已提交
530 531
        p = self.推荐
        if not p:
H
hjdhnx 已提交
532 533
            return self.blank()

H
hjdhnx 已提交
534
        jsp = jsoup(self.homeUrl)
H
hjdhnx 已提交
535 536
        result = {}
        videos = []
H
hjdhnx 已提交
537 538 539 540 541 542 543
        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环境标志
H
hjdhnx 已提交
544
                'oheaders':self.d.oheaders,
H
hjdhnx 已提交
545
                'fetch_params': {'headers': self.headers, 'timeout': self.d.timeout, 'encoding': self.d.encoding},
H
hjdhnx 已提交
546 547 548
                'd': self.d,
                'getParse': self.d.getParse,
                'saveParse': self.d.saveParse,
H
hjdhnx 已提交
549
                'jsp': jsp,'jq':jsp,'setDetail': setDetail,
H
hjdhnx 已提交
550 551 552 553 554 555 556 557 558 559 560 561 562 563
            })
            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:
H
hjdhnx 已提交
564 565 566 567
            if p == '*' and self.一级:
                p = self.一级
                self.double = False
                logger.info(f'首页推荐继承一级: {p}')
H
hjdhnx 已提交
568 569 570 571 572 573
            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)
H
hjdhnx 已提交
574 575
            pp = self.一级.split(';')
            def getPP(p,pn,pp,ppn):
576 577 578 579 580
                try:
                    ps = pp[ppn] if p[pn] == '*' and len(pp) > ppn else p[pn]
                    return ps
                except Exception as e:
                    return ''
H
hjdhnx 已提交
581 582
            p0 = getPP(p,0,pp,0)
            is_json = str(p0).startswith('json:')
H
hjdhnx 已提交
583 584
            if is_json:
                html = self.dealJson(html)
H
hjdhnx 已提交
585 586 587
            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
H
hjdhnx 已提交
588

H
hjdhnx 已提交
589 590 591
            # print(html)
            try:
                if self.double:
H
hjdhnx 已提交
592
                    items = pdfa(html, p0.replace('json:',''))
H
hjdhnx 已提交
593
                    # print(p[0])
H
hjdhnx 已提交
594
                    # print(items)
H
hjdhnx 已提交
595
                    # print(len(items))
596 597 598 599 600 601
                    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)
H
hjdhnx 已提交
602
                    for item in items:
603
                        items2 = pdfa(item,p1)
H
hjdhnx 已提交
604
                        # print(len(items2))
H
hjdhnx 已提交
605 606
                        for item2 in items2:
                            try:
H
hjdhnx 已提交
607 608
                                title = pdfh(item2, p2)
                                # print(title)
H
hjdhnx 已提交
609
                                try:
H
hjdhnx 已提交
610
                                    img = pd(item2, p3)
H
hjdhnx 已提交
611 612
                                except:
                                    img = ''
H
hjdhnx 已提交
613 614 615 616 617
                                try:
                                    desc = pdfh(item2, p4)
                                except:
                                    desc = ''
                                links = [pd(item2, _p5) if not self.detailUrl else pdfh(item2, _p5) for _p5 in p5.split('+')]
H
hjdhnx 已提交
618
                                vid = '$'.join(links)
H
hjdhnx 已提交
619 620 621 622
                                if len(p) > 6 and p[6]:
                                    content = pdfh(item2, p6)
                                else:
                                    content = ''
H
hjdhnx 已提交
623 624
                                if self.二级 == '*':
                                    vid = vid + '@@' + title + '@@' + img
H
hjdhnx 已提交
625
                                videos.append({
H
hjdhnx 已提交
626
                                    "vod_id": vid,
H
hjdhnx 已提交
627 628 629 630 631 632 633 634 635 636 637 638
                                    "vod_name": title,
                                    "vod_pic": img,
                                    "vod_remarks": desc,
                                    "no_use":{
                                        "vod_content": content,
                                        "type_id": 1,
                                        "type_name": "首页推荐",
                                    },
                                })
                            except:
                                pass
                else:
H
hjdhnx 已提交
639
                    items = pdfa(html, p0.replace('json:',''))
H
hjdhnx 已提交
640
                    # print(items)
641 642 643 644 645 646
                    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)

H
hjdhnx 已提交
647
                    for item in items:
H
hjdhnx 已提交
648
                        try:
H
hjdhnx 已提交
649 650 651 652 653 654 655 656 657
                            title = pdfh(item, p1)
                            try:
                                img = pd(item, p2)
                            except:
                                img = ''
                            try:
                                desc = pdfh(item, p3)
                            except:
                                desc = ''
H
hjdhnx 已提交
658
                            # link = pd(item, p[4])
H
hjdhnx 已提交
659
                            links = [pd(item, _p5) if not self.detailUrl else pdfh(item, _p5) for _p5 in p4.split('+')]
H
hjdhnx 已提交
660
                            vid = '$'.join(links)
H
hjdhnx 已提交
661 662 663 664
                            if len(p) > 5 and p[5]:
                                content = pdfh(item, p5)
                            else:
                                content = ''
H
hjdhnx 已提交
665 666
                            if self.二级 == '*':
                                vid = vid + '@@' + title + '@@' + img
H
hjdhnx 已提交
667
                            videos.append({
H
hjdhnx 已提交
668
                                "vod_id": vid,
H
hjdhnx 已提交
669 670 671
                                "vod_name": title,
                                "vod_pic": img,
                                "vod_remarks": desc,
H
hjdhnx 已提交
672
                                "no_use": {
673 674 675 676
                                    "vod_content": content,
                                    "type_id": 1,
                                    "type_name": "首页推荐",
                                },
H
hjdhnx 已提交
677 678 679
                            })
                        except:
                            pass
H
hjdhnx 已提交
680

H
hjdhnx 已提交
681
            # result['list'] = videos[min((fypage-1)*self.limit,len(videos)-1):min(fypage*self.limit,len(videos))]
H
hjdhnx 已提交
682 683 684
            except Exception as e:
                logger.info(f'首页内容获取失败:{e}')
                return self.blank()
H
hjdhnx 已提交
685 686 687 688
        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.图片来源}"
H
hjdhnx 已提交
689
        result['list'] = videos
H
hjdhnx 已提交
690
        # print(videos)
H
hjdhnx 已提交
691 692 693 694 695 696 697 698 699 700 701
        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
H
hjdhnx 已提交
702

H
hjdhnx 已提交
703
    def categoryContent(self, fyclass, fypage, fl=None):
H
hjdhnx 已提交
704 705 706 707
        """
        一级带分类的数据返回
        :param fyclass: 分类标识
        :param fypage: 页码
H
hjdhnx 已提交
708
        :param fl: 筛选
H
hjdhnx 已提交
709 710
        :return: cms一级数据
        """
H
hjdhnx 已提交
711 712 713

        if fl is None:
            fl = {}
714
        # print(f'fl:{fl}')
H
hjdhnx 已提交
715 716 717 718 719 720 721 722 723 724
        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)
H
hjdhnx 已提交
725 726 727 728 729 730 731 732 733 734 735 736
        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)
H
hjdhnx 已提交
737
        url = self.url.replace('fyclass',fyclass)
H
hjdhnx 已提交
738 739 740 741
        if fypage == 1 and self.test('[\[\]]',url):
            url = url.split('[')[1].split(']')[0]
        elif fypage > 1 and self.test('[\[\]]',url):
            url = url.split('[')[0]
H
hjdhnx 已提交
742 743 744 745 746 747 748
        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)
749
            # print(f'url渲染:{url}')
H
hjdhnx 已提交
750 751 752 753 754 755 756 757
            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)
H
hjdhnx 已提交
758 759 760 761 762 763 764 765 766 767 768 769 770
        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 = {}
                exec(f'cnt_pg={cnt_page}', cnt_ctx)
                cnt_pg = str(cnt_ctx['cnt_pg']) # 计算表达式的结果
                url = url.replace(url_rep,str(cnt_pg)).replace('(','').replace(')','')
H
hjdhnx 已提交
771
                # print(url)
H
hjdhnx 已提交
772 773
            else:
                url = url.replace('fypage',pg)
H
hjdhnx 已提交
774

H
hjdhnx 已提交
775
        # print(url)
H
hjdhnx 已提交
776
        logger.info(url)
H
hjdhnx 已提交
777
        p = self.一级
H
hjdhnx 已提交
778 779
        jsp = jsoup(self.url)
        videos = []
H
hjdhnx 已提交
780 781 782 783 784
        is_js = isinstance(p, str) and str(p).startswith('js:')  # 是js
        if is_js:
            headers['Referer'] = getHome(url)
            py_ctx.update({
                'input': url,
H
hjdhnx 已提交
785
                'TYPE': 'cate',  # 海阔js环境标志
H
hjdhnx 已提交
786
                'oheaders': self.d.oheaders,
H
hjdhnx 已提交
787
                'fetch_params': {'headers': self.headers, 'timeout': self.d.timeout, 'encoding': self.d.encoding},
H
hjdhnx 已提交
788
                'd': self.d,
H
hjdhnx 已提交
789 790 791
                'MY_CATE':fyclass, # 分类id
                'MY_FL':fl, # 筛选
                'MY_PAGE':fypage,  # 页数
H
hjdhnx 已提交
792 793 794
                'detailUrl':self.detailUrl or '', # 详情页链接
                'getParse': self.d.getParse,
                'saveParse': self.d.saveParse,
H
hjdhnx 已提交
795
                'jsp': jsp,'jq':jsp, 'setDetail': setDetail,
H
hjdhnx 已提交
796 797 798 799 800 801 802 803
            })
            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')
H
hjdhnx 已提交
804
            # print('vods:',vods)
H
hjdhnx 已提交
805 806 807 808 809
            if isinstance(vods, JsObjectWrapper):
                videos = vods.to_list()

        else:
            p = p.split(';')  # 解析
H
hjdhnx 已提交
810
            # print(len(p))
811
            # print(p)
H
hjdhnx 已提交
812 813 814 815 816 817 818 819 820 821 822 823
            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 = []
H
hjdhnx 已提交
824
            try:
H
hjdhnx 已提交
825
                r = requests.get(url, headers=self.headers, timeout=self.timeout,verify=False)
H
hjdhnx 已提交
826
                html = self.checkHtml(r)
H
hjdhnx 已提交
827
                print(self.headers)
H
hjdhnx 已提交
828
                # print(html)
H
hjdhnx 已提交
829
                if is_json:
H
hjdhnx 已提交
830
                    html = self.dealJson(html)
H
hjdhnx 已提交
831
                    html = json.loads(html)
H
hjdhnx 已提交
832 833 834
                # else:
                #     soup = bs4.BeautifulSoup(html, 'lxml')
                #     html = soup.prettify()
H
hjdhnx 已提交
835
                # print(html)
H
hjdhnx 已提交
836 837
                # with open('1.html',mode='w+',encoding='utf-8') as f:
                #     f.write(html)
H
hjdhnx 已提交
838 839
                items = pdfa(html,p[0].replace('json:','',1))
            except:
H
hjdhnx 已提交
840
                pass
H
hjdhnx 已提交
841 842 843 844 845 846 847 848 849 850 851
            # 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")
H
hjdhnx 已提交
852 853 854 855
                    vod_id = f'{fyclass}${link}' if self.detailUrl else link # 分类,播放链接
                    if self.二级 == '*':
                        vod_id = vod_id+'@@'+title+'@@'+img

H
hjdhnx 已提交
856
                    videos.append({
H
hjdhnx 已提交
857
                        "vod_id": vod_id,
H
hjdhnx 已提交
858 859 860 861 862 863 864 865
                        "vod_name": title,
                        "vod_pic": img,
                        "vod_remarks": desc,
                        "vod_content": content,
                    })
                except Exception as e:
                    print(f'发生了错误:{e}')
                    pass
H
hjdhnx 已提交
866 867 868 869 870

        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.图片来源}"
871
        print('videos:',videos)
H
hjdhnx 已提交
872 873
        limit = 40
        cnt = 9999 if len(videos) > 0 else 0
H
hjdhnx 已提交
874 875 876 877
        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])
H
hjdhnx 已提交
878 879
        result['list'] = videos
        result['page'] = fypage
H
hjdhnx 已提交
880
        result['pagecount'] = pagecount or max(cnt,fypage)
H
hjdhnx 已提交
881 882 883
        result['limit'] = limit
        result['total'] = cnt
        # print(result)
H
hjdhnx 已提交
884
        # print(result['pagecount'])
H
hjdhnx 已提交
885
        logger.info(f'{self.getName()}获取分类{fyclass}{fypage}页耗时:{get_interval(t1)}毫秒,共计{round(len(str(result)) / 1000, 2)} kb')
H
hjdhnx 已提交
886 887 888 889 890 891 892
        nodata = {
            'list': [{'vod_name': '无数据,防无限请求', 'vod_id': 'no_data', 'vod_remarks': '不要点,会崩的',
                    'vod_pic': 'https://ghproxy.com/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
H
hjdhnx 已提交
893

894 895 896 897
    def 二级渲染(self,parse_str:'str|dict',**kwargs):
        # *args是不定长参数 列表
        # ** args是不定长参数字典
        p = parse_str  # 二级传递解析表达式 js的obj json对象
H
hjdhnx 已提交
898 899
        detailUrl = kwargs.get('detailUrl','') # 不定长字典传递的二级详情页vod_id详情处理数据
        orId = kwargs.get('orId','') # 不定长字典传递的二级详情页vod_id原始数据
900 901 902 903 904 905
        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','') # 二级传递的分类名称,可以得知进去的类别
H
hjdhnx 已提交
906
        play_url = self.play_url
H
hjdhnx 已提交
907 908 909 910 911 912 913
        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
H
hjdhnx 已提交
914 915
        if self.play_json:
            play_url = play_url.replace('&play_url=', '&type=json&play_url=')
916 917 918 919 920 921
        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
H
hjdhnx 已提交
922 923 924 925
            vod['vod_id'] = orId
            vod['vod_name'] = vod_name
            vod['vod_pic'] = vod_pic
            vod['vod_play_url'] = '嗅探播放$' + play_url + url.split('@@')[0]
926 927 928 929 930 931 932 933 934

        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
H
hjdhnx 已提交
935 936
            vod['vod_id'] = orId
            if not html: # 没传递html参数接detailUrl下来智能获取
H
hjdhnx 已提交
937
                r = requests.get(url, headers=self.headers, timeout=self.timeout,verify=False)
938 939 940 941
                html = self.checkHtml(r)
                if is_json:
                    html = self.dealJson(html)
                    html = json.loads(html)
942 943

            tt1 = time()
944 945
            if p.get('title'):
                p1 = p['title'].split(';')
946 947
                vod['vod_name'] = pdfh(html, p1[0]).replace('\n', ' ').strip()
                vod['type_name'] = pdfh(html, p1[1]).replace('\n',' ').strip() if len(p1)>1 else ''
948 949 950
            if p.get('desc'):
                try:
                    p1 = p['desc'].split(';')
951 952 953 954 955
                    vod['vod_remarks'] = pdfh(html, p1[0]).replace('\n', '').strip()
                    vod['vod_year'] = pdfh(html, p1[1]).replace('\n', ' ').strip() if len(p1) > 1 else ''
                    vod['vod_area'] = pdfh(html, p1[2]).replace('\n', ' ').strip() if len(p1) > 2 else ''
                    vod['vod_actor'] = pdfh(html, p1[3]).replace('\n', ' ').strip() if len(p1) > 3 else ''
                    vod['vod_director'] = pdfh(html, p1[4]).replace('\n', ' ').strip() if len(p1) > 4 else ''
956 957 958 959 960 961 962
                except:
                    pass

            if p.get('content'):
                p1 = p['content'].split(';')
                try:
                    content = '\n'.join([pdfh(html, i).replace('\n', ' ') for i in p1])
963
                    vod['vod_content'] = content
964 965 966 967 968 969 970
                except:
                    pass

            if p.get('img'):
                p1 = p['img']
                try:
                    img = pd(html, p1)
971
                    vod['vod_pic'] = img
972 973 974 975 976
                except Exception as e:
                    logger.info(f'二级图片定位失败,但不影响使用{e}')

            vod_play_from = '$$$'
            playFrom = []
H
hjdhnx 已提交
977 978
            init_flag = {'ctx':False}
            def js_pre():
979 980 981 982 983
                headers['Referer'] = getHome(url)
                py_ctx.update({
                    'input': url,
                    'html': html,
                    'TYPE': 'detail',  # 海阔js环境标志
H
hjdhnx 已提交
984
                    'MY_CATE': fyclass,  # 分类id
985 986 987 988 989
                    '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,
H
hjdhnx 已提交
990
                    'jsp': jsp,'jq':jsp, 'setDetail': setDetail,'play_url':play_url
991
                })
H
hjdhnx 已提交
992 993 994 995
                init_flag['ctx'] = True
            if p.get('重定向') and str(p['重定向']).startswith('js:'):
                if not init_flag['ctx']:
                    js_pre()
996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
                ctx = py_ctx
                # print(ctx)
                rcode = p['重定向'].replace('js:', '', 1)
                jscode = getPreJs() + rcode
                # print(jscode)
                loader, _ = runJScode(jscode, ctx=ctx)
                # print(loader.toString())
                logger.info(f'开始执行二级重定向代码:{rcode}')
                html = loader.eval('html')
                if isinstance(vod, JsObjectWrapper):
                    html = str(html)

            if p.get('tabs'):
                vodHeader = []
H
hjdhnx 已提交
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
                if str(p['tabs']).startswith('js:'):
                    if not init_flag['ctx']:
                        js_pre()
                    ctx = py_ctx
                    rcode = p['tabs'].replace('js:', '', 1)
                    jscode = getPreJs() + rcode
                    # print(jscode)
                    loader, _ = runJScode(jscode, ctx=ctx)
                    # print(loader.toString())
                    logger.info(f'开始执行tabs代码:{rcode}')
                    vHeader = loader.eval('TABS')
                    if isinstance(vod, JsObjectWrapper):
                        vHeader = vHeader.to_list()
1023
                    vodHeader = vHeader
H
hjdhnx 已提交
1024
                else:
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
                    tab_parse = p['tabs'].split(';')[0]
                    # print('tab_parse:',tab_parse)
                    vHeader = pdfa(html, tab_parse)
                    # print(vHeader)
                    print(f'二级线路定位列表数:{len((vHeader))}')
                    # print(vHeader[0].outerHtml())
                    # print(vHeader[0].toString())
                    # from lxml import etree
                    # print(str(etree.tostring(vHeader[0], pretty_print=True), 'utf-8'))
                    from lxml.html import tostring as html2str
                    # print(html2str(vHeader[0].root).decode('utf-8'))
H
hjdhnx 已提交
1036 1037
                    tab_text = p.get('tab_text','') or 'body&&Text'
                    # print('tab_text:'+tab_text)
H
hjdhnx 已提交
1038 1039 1040
                    if not is_json:
                        for v in vHeader:
                            # 过滤排除掉线路标题
H
hjdhnx 已提交
1041 1042
                            # v_title = pq(v).text()
                            v_title = pdfh(v,tab_text).strip()
1043
                            # print(v_title)
H
hjdhnx 已提交
1044 1045 1046 1047 1048
                            if self.tab_exclude and jsp.test(self.tab_exclude, v_title):
                                continue
                            vodHeader.append(v_title)
                    else:
                        vodHeader = vHeader
1049
                    print(f'过滤后真实线路列表数:{len((vodHeader))} {vodHeader}')
1050 1051 1052 1053
            else:
                vodHeader = ['道长在线']

            # print(vodHeader)
H
hjdhnx 已提交
1054
            # print(vod)
H
hjdhnx 已提交
1055
            new_map = {}
1056
            for v in vodHeader:
H
hjdhnx 已提交
1057 1058 1059 1060 1061 1062
                if not v in new_map:
                    new_map[v] = 1
                else:
                    new_map[v] += 1
                if new_map[v] > 1:
                    v = f'{v}{new_map[v]-1}'
1063 1064 1065 1066 1067 1068
                playFrom.append(v)
            vod_play_from = vod_play_from.join(playFrom)

            vod_play_url = '$$$'
            vod_tab_list = []
            if p.get('lists'):
H
hjdhnx 已提交
1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
                if str(p['lists']).startswith('js:'):
                    if not init_flag['ctx']:
                        js_pre()
                    ctx = py_ctx
                    ctx['TABS'] = vodHeader # 把选集列表传过去
                    rcode = p['lists'].replace('js:', '', 1)
                    jscode = getPreJs() + rcode
                    # print(jscode)
                    loader, _ = runJScode(jscode, ctx=ctx)
                    # print(loader.toString())
                    logger.info(f'开始执行lists代码:{rcode}')
                    vlists = loader.eval('LISTS')
                    if isinstance(vod, JsObjectWrapper):
                        vlists = vlists.to_list() # [['第1集$http://1.mp4','第2集$http://2.mp4'],['第3集$http://1.mp4','第4集$http://2.mp4']]
H
hjdhnx 已提交
1083 1084 1085 1086 1087
                    for i in range(len(vlists)):
                        try:
                            vlists[i] = list(map(lambda x:'$'.join(x.split('$')[:2]),vlists[i]))
                        except Exception as e:
                            logger.info(f'LISTS格式化发生错误:{e}')
H
hjdhnx 已提交
1088 1089
                    vod_play_url = vod_play_url.join(list(map(lambda x:'#'.join(x),vlists)))
                else:
H
hjdhnx 已提交
1090 1091 1092 1093 1094
                    list_text = p.get('list_text','') or 'body&&Text'
                    list_url = p.get('list_url','') or 'a&&href'
                    print('list_text:' + list_text)
                    print('list_url:' + list_url)
                    is_tab_js = p['tabs'].strip().startswith('js:')
H
hjdhnx 已提交
1095 1096
                    for i in range(len(vodHeader)):
                        tab_name = str(vodHeader[i])
1097
                        # print(tab_name)
H
hjdhnx 已提交
1098
                        tab_ext = p['tabs'].split(';')[1] if len(p['tabs'].split(';')) > 1 and not is_tab_js else ''
H
hjdhnx 已提交
1099 1100
                        p1 = p['lists'].replace('#idv', tab_name).replace('#id', str(i))
                        tab_ext = tab_ext.replace('#idv', tab_name).replace('#id', str(i))
1101
                        # print(p1)
H
hjdhnx 已提交
1102 1103 1104
                        vodList = pdfa(html, p1)  # 1条线路的选集列表
                        # print(vodList)
                        # vodList = [pq(i).text()+'$'+pd(i,'a&&href') for i in vodList]  # 拼接成 名称$链接
H
hjdhnx 已提交
1105
                        # pq(i).text()
H
hjdhnx 已提交
1106
                        if self.play_parse:  # 自动base64编码
H
hjdhnx 已提交
1107
                            vodList = [(pdfh(html, tab_ext) if tab_ext else tab_name) + '$' + play_url + encodeUrl(i) for i
H
hjdhnx 已提交
1108
                                       in vodList] if is_json else \
H
hjdhnx 已提交
1109
                                [pdfh(i,list_text) + '$' + play_url + encodeUrl(pd(i, list_url)) for i in vodList]  # 拼接成 名称$链接
H
hjdhnx 已提交
1110
                        else:
H
hjdhnx 已提交
1111
                            vodList = [(pdfh(html, tab_ext) if tab_ext else tab_name) + '$' + play_url + i for i in
H
hjdhnx 已提交
1112
                                       vodList] if is_json else \
H
hjdhnx 已提交
1113
                                [pdfh(i,list_text) + '$' + play_url + pd(i, list_url) for i in vodList]  # 拼接成 名称$链接
H
hjdhnx 已提交
1114 1115 1116 1117

                        # print(vodList)
                        vodList = forceOrder(vodList,option=lambda x:x.split('$')[0])
                        # print(vodList)
H
hjdhnx 已提交
1118
                        vlist = '#'.join(vodList)  # 拼多个选集
H
hjdhnx 已提交
1119
                        # print(vlist)
H
hjdhnx 已提交
1120 1121 1122
                        vod_tab_list.append(vlist)
                    vod_play_url = vod_play_url.join(vod_tab_list)

1123
            vod_play_url_str = vod_play_url[:min(len(vod_play_url),500)]
1124
            print(vod_play_url_str)
1125 1126 1127 1128
            vod['vod_play_from'] = vod_play_from
            # print(vod_play_from)
            vod['vod_play_url'] = vod_play_url

1129 1130
            logger.info(f'{self.getName()}仅二级渲染{len(vod_play_url.split("$$$")[0].split("$"))}集耗时:{get_interval(tt1)}毫秒,共计{round(len(str(vod)) / 1000, 2)} kb')

1131 1132 1133 1134
        if show_name:
            vod['vod_content'] = f'({self.id}){vod.get("vod_content", "")}'
        return vod

H
hjdhnx 已提交
1135
    def detailOneVod(self,id,fyclass='',show_name=False):
1136
        vod = self.blank_vod()
H
hjdhnx 已提交
1137 1138
        orId = str(id)
        detailUrl = orId.split('@@')[0]
H
hjdhnx 已提交
1139
        # print(detailUrl)
H
hjdhnx 已提交
1140
        if not detailUrl.startswith('http') and not '/' in detailUrl:
H
hjdhnx 已提交
1141
            url = self.detailUrl.replace('fyid', detailUrl).replace('fyclass',fyclass)
H
hjdhnx 已提交
1142
            # print(url)
H
hjdhnx 已提交
1143 1144
        elif '/' in detailUrl:
            url = urljoin(self.homeUrl,detailUrl)
H
hjdhnx 已提交
1145 1146
        else:
            url = detailUrl
H
hjdhnx 已提交
1147
        logger.info(f'进入详情页: {url}')
H
hjdhnx 已提交
1148 1149
        try:
            p = self.二级  # 解析
H
hjdhnx 已提交
1150
            jsp = jsoup(url) if url.startswith('http') else jsoup(self.url)
H
hjdhnx 已提交
1151 1152 1153
            is_js = isinstance(p,str) and str(p).startswith('js:') # 是js
            if is_js:
                headers['Referer'] = getHome(url)
H
hjdhnx 已提交
1154 1155 1156
                play_url = self.play_url
                if self.play_json:
                    play_url = play_url.replace('&play_url=', '&type=json&play_url=')
H
hjdhnx 已提交
1157 1158
                py_ctx.update({
                    'input': url,
H
hjdhnx 已提交
1159
                    'TYPE': 'detail',  # 海阔js环境标志
H
hjdhnx 已提交
1160
                    # 'VID': id,  # 传递的vod_id
1161
                    '二级': self.二级渲染,  # 二级解析函数,可以解析dict
H
hjdhnx 已提交
1162
                    'MY_CATE': fyclass,  # 分类id
H
hjdhnx 已提交
1163
                    'oheaders': self.d.oheaders,
H
hjdhnx 已提交
1164
                    'fetch_params': {'headers': self.headers, 'timeout': self.d.timeout, 'encoding': self.d.encoding},
H
hjdhnx 已提交
1165 1166 1167
                    'd': self.d,
                    'getParse': self.d.getParse,
                    'saveParse': self.d.saveParse,
H
hjdhnx 已提交
1168
                    'jsp':jsp,'jq':jsp,'setDetail':setDetail,'play_url':play_url
H
hjdhnx 已提交
1169 1170 1171 1172 1173 1174 1175
                })
                ctx = py_ctx
                # print(ctx)
                jscode = getPreJs() + p.replace('js:','',1)
                # print(jscode)
                loader, _ = runJScode(jscode, ctx=ctx)
                # print(loader.toString())
1176
                vod = loader.eval('VOD')
H
hjdhnx 已提交
1177 1178
                if isinstance(vod,JsObjectWrapper):
                    vod = vod.to_dict()
1179 1180
                    if show_name:
                        vod['vod_content'] = f'({self.id}){vod.get("vod_content", "")}'
H
hjdhnx 已提交
1181
                else:
1182
                    vod = self.blank_vod()
H
hjdhnx 已提交
1183
            else:
H
hjdhnx 已提交
1184
                vod = self.二级渲染(p,detailUrl=detailUrl,orId=orId,url=url,vod=vod,show_name=show_name,jsp=jsp,fyclass=fyclass)
H
hjdhnx 已提交
1185 1186
        except Exception as e:
            logger.info(f'{self.getName()}获取单个详情页{detailUrl}出错{e}')
H
hjdhnx 已提交
1187 1188 1189
        if self.图片来源:
            if vod.get('vod_pic','') and str(vod['vod_pic']).startswith('http'):
                vod['vod_pic'] = f"{vod['vod_pic']}{self.图片来源}"
H
hjdhnx 已提交
1190
        if not vod.get('vod_id'):
H
hjdhnx 已提交
1191
            vod['vod_id'] = orId
H
hjdhnx 已提交
1192
        # print(vod)
H
hjdhnx 已提交
1193 1194
        return vod

H
hjdhnx 已提交
1195
    def detailContent(self, fypage, array,show_name=False):
H
hjdhnx 已提交
1196 1197 1198 1199 1200
        """
        cms二级数据
        :param array:
        :return:
        """
H
hjdhnx 已提交
1201
        # print('进入二级')
H
hjdhnx 已提交
1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213
        t1 = time()
        array = array if len(array) <= self.limit else array[(fypage-1)*self.limit:min(self.limit*fypage,len(array))]
        thread_pool = ThreadPoolExecutor(min(self.limit,len(array)))  # 定义线程池来启动多线程执行此任务
        obj_list = []
        try:
            for vod_url in array:
                # print(vod_url)
                vod_class = ''
                if vod_url.find('$') > -1:
                    tmp = vod_url.split('$')
                    vod_class = tmp[0]
                    vod_url = tmp[1]
H
hjdhnx 已提交
1214
                obj = thread_pool.submit(self.detailOneVod, vod_url,vod_class,show_name)
H
hjdhnx 已提交
1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226
                obj_list.append(obj)
            thread_pool.shutdown(wait=True)  # 等待所有子线程并行完毕
            vod_list = [obj.result() for obj in obj_list]
            result = {
                'list': vod_list
            }
            logger.info(f'{self.getName()}获取详情页耗时:{get_interval(t1)}毫秒,共计{round(len(str(result)) / 1000, 2)} kb')
        except Exception as e:
            result = {
                'list': []
            }
            logger.info(f'{self.getName()}获取详情页耗时:{get_interval(t1)}毫秒,发生错误:{e}')
H
hjdhnx 已提交
1227
        # print(result)
H
hjdhnx 已提交
1228 1229
        return result

H
hjdhnx 已提交
1230
    def searchContent(self, key, fypage=1,show_name=False):
1231 1232 1233
        if self.encoding and str(self.encoding).startswith('gb'):
            key = quote(key.encode('utf-8').decode('utf-8').encode(self.encoding,'ignore'))
            # print(key)
H
hjdhnx 已提交
1234 1235 1236 1237 1238 1239 1240
        pg = str(fypage)
        if not self.searchUrl:
            return self.blank()
        url = self.searchUrl.replace('**', key).replace('fypage',pg)
        logger.info(f'{self.getName()}搜索链接:{url}')
        if not self.搜索:
            return self.blank()
H
hjdhnx 已提交
1241 1242
        # p = self.一级.split(';') if self.搜索 == '*' and self.一级 else self.搜索.split(';')  # 解析
        p = self.一级 if self.搜索 == '*' and self.一级 else self.搜索
H
hjdhnx 已提交
1243
        pp = self.一级.split(';')
H
hjdhnx 已提交
1244
        jsp = jsoup(url) if url.startswith('http') else jsoup(self.url)
H
hjdhnx 已提交
1245
        videos = []
H
hjdhnx 已提交
1246
        is_js = isinstance(p, str) and str(p).startswith('js:')  # 是js
H
hjdhnx 已提交
1247 1248

        def getPP(p, pn, pp, ppn):
H
hjdhnx 已提交
1249 1250 1251 1252 1253
            try:
                ps = pp[ppn] if p[pn] == '*' and len(pp) > ppn else p[pn]
                return ps
            except:
                return ''
H
hjdhnx 已提交
1254 1255 1256 1257
        if is_js:
            headers['Referer'] = getHome(url)
            py_ctx.update({
                'input': url,
H
hjdhnx 已提交
1258
                'oheaders': self.d.oheaders,
H
hjdhnx 已提交
1259
                'fetch_params': {'headers': self.headers, 'timeout': self.d.timeout, 'encoding': self.d.encoding},
H
hjdhnx 已提交
1260
                'd': self.d,
H
hjdhnx 已提交
1261
                'MY_PAGE': fypage,
H
hjdhnx 已提交
1262
                'KEY': key,  # 搜索关键字
H
hjdhnx 已提交
1263
                'TYPE': 'search',  # 海阔js环境标志
H
hjdhnx 已提交
1264 1265
                'detailUrl': self.detailUrl or '',
                # 详情页链接
H
hjdhnx 已提交
1266 1267
                'getParse': self.d.getParse,
                'saveParse': self.d.saveParse,
H
hjdhnx 已提交
1268
                'jsp': jsp,'jq':jsp, 'setDetail': setDetail,
H
hjdhnx 已提交
1269 1270 1271 1272 1273 1274 1275 1276
            })
            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')
H
hjdhnx 已提交
1277
            # print(len(vods),type(vods))
H
hjdhnx 已提交
1278 1279
            if isinstance(vods, JsObjectWrapper):
                videos = vods.to_list()
H
hjdhnx 已提交
1280
            # print(videos)
H
hjdhnx 已提交
1281 1282 1283 1284 1285 1286 1287 1288 1289 1290
        else:
            p = p.split(';')
            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
            pq = jsp.pq
            try:
H
hjdhnx 已提交
1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305
                req_method = url.split(';')[1].lower() if len(url.split(';'))>1 else 'get'
                if req_method == 'post':
                    rurls = url.split(';')[0].split('#')
                    rurl = rurls[0]
                    params = rurls[1] if len(rurls)>1 else ''
                    # params = quote(params)
                    print(f'rurl:{rurl},params:{params}')
                    new_dict = {}
                    new_tmp = params.split('&')
                    # print(new_tmp)
                    for i in new_tmp:
                        new_dict[i.split('=')[0]] = i.split('=')[1]
                    # data = ujson.dumps(new_dict)
                    data = new_dict
                    # print(data)
H
hjdhnx 已提交
1306
                    logger.info(self.headers)
H
hjdhnx 已提交
1307 1308 1309 1310 1311 1312 1313 1314
                    r = requests.post(rurl, headers=self.headers,data=data, timeout=self.timeout, verify=False)
                elif req_method == 'postjson':
                    rurls = url.split(';')[0].split('#')
                    rurl = rurls[0]
                    params = rurls[1] if len(rurls) > 1 else '{}'
                    headers_cp = self.headers.copy()
                    headers_cp.update({'Content-Type':'application/json'})
                    try:
H
hjdhnx 已提交
1315
                        params = ujson.dumps(ujson.loads(params))
H
hjdhnx 已提交
1316 1317
                    except:
                        params = '{}'
H
hjdhnx 已提交
1318
                    # params = params.encode()
H
hjdhnx 已提交
1319
                    logger.info(headers_cp)
H
hjdhnx 已提交
1320
                    logger.info(params)
H
hjdhnx 已提交
1321 1322 1323
                    r = requests.post(rurl, headers=headers_cp, data=params, timeout=self.timeout, verify=False)
                else:
                    r = requests.get(url, headers=self.headers,timeout=self.timeout,verify=False)
H
hjdhnx 已提交
1324 1325
                html = self.checkHtml(r)
                if is_json:
H
hjdhnx 已提交
1326
                    html = self.dealJson(html)
H
hjdhnx 已提交
1327
                    html = json.loads(html)
H
hjdhnx 已提交
1328

H
hjdhnx 已提交
1329 1330
                # if not is_json and html.find('输入验证码') > -1:
                if not is_json and re.search('系统安全验证|输入验证码',html,re.M|re.S):
H
hjdhnx 已提交
1331 1332 1333 1334 1335 1336 1337 1338
                    cookie = verifyCode(url,self.headers,self.timeout,self.retry_count,self.ocr_api)
                    # cookie = ''
                    if not cookie:
                        return {
                            'list': videos
                        }
                    self.saveCookie(cookie)
                    self.headers['cookie'] = cookie
H
hjdhnx 已提交
1339
                    r = requests.get(url, headers=self.headers, timeout=self.timeout,verify=False)
H
hjdhnx 已提交
1340 1341
                    r.encoding = self.encoding
                    html = r.text
H
hjdhnx 已提交
1342
                if not show_name and not str(html).find(key) > -1:
H
hjdhnx 已提交
1343 1344
                    logger.info('搜索结果源码未包含关键字,疑似搜索失败,正为您打印结果源码')
                    print(html)
H
hjdhnx 已提交
1345

H
hjdhnx 已提交
1346 1347
                p0 = getPP(p,0,pp,0)
                items = pdfa(html,p0.replace('json:','',1))
H
hjdhnx 已提交
1348
                # print(len(items),items)
H
hjdhnx 已提交
1349
                videos = []
H
hjdhnx 已提交
1350 1351 1352 1353 1354 1355
                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)

H
hjdhnx 已提交
1356 1357
                for item in items:
                    # print(item)
H
hjdhnx 已提交
1358
                    try:
H
hjdhnx 已提交
1359
                        # title = pdfh(item, p[1])
H
hjdhnx 已提交
1360
                        title = ''.join([pdfh(item, i) for i in p1.split('||')])
H
hjdhnx 已提交
1361
                        try:
H
hjdhnx 已提交
1362
                            img = pd(item, p2)
H
hjdhnx 已提交
1363 1364 1365
                        except:
                            img = ''
                        try:
H
hjdhnx 已提交
1366
                            desc = pdfh(item, p3)
H
hjdhnx 已提交
1367 1368
                        except:
                            desc = ''
H
hjdhnx 已提交
1369 1370 1371
                        if len(p) > 5 and p[5]:
                            content = pdfh(item, p5)
                        else:
H
hjdhnx 已提交
1372 1373
                            content = ''
                        # link = '$'.join([pd(item, p4) for p4 in p[4].split('+')])
H
hjdhnx 已提交
1374
                        links = [pd(item, _p4) if not self.detailUrl else pdfh(item, _p4) for _p4 in p4.split('+')]
H
hjdhnx 已提交
1375 1376 1377
                        link = '$'.join(links)
                        # print(content)
                        # sid = self.regStr(sid, "/video/(\\S+).html")
H
hjdhnx 已提交
1378 1379 1380
                        vod_id = link
                        if self.二级 == '*':
                            vod_id = vod_id + '@@' + title + '@@' + img
H
hjdhnx 已提交
1381
                        videos.append({
H
hjdhnx 已提交
1382
                            "vod_id": vod_id,
H
hjdhnx 已提交
1383 1384 1385 1386 1387
                            "vod_name": title,
                            "vod_pic": img,
                            "vod_remarks": desc,
                            "vod_content": content, # 无用参数
                        })
H
hjdhnx 已提交
1388
                    except Exception as e:
H
hjdhnx 已提交
1389
                        print(f'搜索列表解析发生错误:{e}')
H
hjdhnx 已提交
1390 1391 1392 1393
                        pass
                # print(videos)
            except Exception as e:
                logger.info(f'搜索{self.getName()}发生错误:{e}')
H
hjdhnx 已提交
1394 1395 1396 1397
        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.图片来源}"
H
hjdhnx 已提交
1398 1399 1400 1401 1402
        if show_name and len(videos) > 0:
            for video in videos:
                video['vod_name'] = self.id + ' '+video['vod_name']
                video['vod_rule'] = self.id
                video['vod_id'] = video['vod_id'] +'#' + self.id
H
hjdhnx 已提交
1403 1404 1405 1406 1407 1408
        result = {
            'list': videos
        }
        return result

    def playContent(self, play_url,jxs=None,flag=None):
1409
        # flag参数只有类型为4的时候才有,可以忽略
H
hjdhnx 已提交
1410
        # logger.info('播放免嗅地址: ' + self.play_url)
1411
        # 注意:全局flags里的视频没法执行免嗅代码,因为会自动拦截去调用解析: url=yoursite:5705/vod?play_url=xxxx
H
hjdhnx 已提交
1412 1413
        if not jxs:
            jxs = []
H
hjdhnx 已提交
1414

H
hjdhnx 已提交
1415 1416 1417
        # print(play_url)
        if play_url.find('http') == -1: # 字符串看起来被编码的
            try:
H
hjdhnx 已提交
1418
                play_url = base64Decode(play_url) # 自动base64解码
H
hjdhnx 已提交
1419 1420
            except:
                pass
H
hjdhnx 已提交
1421 1422
        # print(unquote(play_url))
        play_url = unquote(play_url)
H
hjdhnx 已提交
1423 1424
        origin_play_url = play_url
        print(origin_play_url)
H
hjdhnx 已提交
1425 1426 1427 1428 1429 1430 1431
        if self.lazy:
            print(f'{play_url}->开始执行免嗅代码{type(self.lazy)}->{self.lazy}')
            t1 = time()
            try:
                if type(self.lazy) == JsObjectWrapper:
                    logger.info(f'lazy非纯文本免嗅失败耗时:{get_interval(t1)}毫秒,播放地址:{play_url}')

H
hjdhnx 已提交
1432
                elif str(self.lazy).startswith('py:'):
H
hjdhnx 已提交
1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444
                    pycode = runPy(self.lazy)
                    if pycode:
                        # print(pycode)
                        pos = pycode.find('def lazyParse')
                        if pos < 0:
                            return play_url
                        pyenv = safePython(self.lazy,pycode[pos:])
                        lazy_url = pyenv.action_task_exec('lazyParse',[play_url,self.d])
                        logger.info(f'py免嗅耗时:{get_interval(t1)}毫秒,播放地址:{lazy_url}')
                        if isinstance(lazy_url,str) and lazy_url.startswith('http'):
                            play_url = lazy_url
                else:
H
hjdhnx 已提交
1445
                    jscode = str(self.lazy).strip().replace('js:', '', 1) if str(self.lazy).startswith('js:') else js_code
H
hjdhnx 已提交
1446
                    jsp = jsoup(self.url)
H
hjdhnx 已提交
1447 1448 1449 1450 1451
                    # jscode = f'var input={play_url};{jscode}'
                    # print(jscode)
                    headers['Referer'] = getHome(play_url)
                    py_ctx.update({
                        'input': play_url,
H
hjdhnx 已提交
1452
                        'oheaders': self.d.oheaders,
H
hjdhnx 已提交
1453
                        'fetch_params':{'headers':self.headers,'timeout':self.d.timeout,'encoding':self.d.encoding},
H
hjdhnx 已提交
1454 1455 1456 1457
                        'd': self.d,
                        'jxs':jxs,
                        'getParse':self.d.getParse,
                        'saveParse':self.d.saveParse,
H
hjdhnx 已提交
1458
                        'jsp': jsp,
H
hjdhnx 已提交
1459
                        'jq': jsp,
H
hjdhnx 已提交
1460
                        'pdfh': self.d.jsp.pdfh,
H
优化  
hjdhnx 已提交
1461
                        'pdfa': self.d.jsp.pdfa, 'pd': self.d.jsp.pd,'play_url':self.play_url
H
hjdhnx 已提交
1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474
                    })
                    ctx = py_ctx
                    # print(ctx)
                    jscode = getPreJs() + jscode
                    # print(jscode)
                    loader,_ = runJScode(jscode,ctx=ctx)
                    # print(loader.toString())
                    play_url = loader.eval('input')
                    if isinstance(play_url,JsObjectWrapper):
                        play_url = play_url.to_dict()
                    # print(type(play_url))
                    # print(play_url)
                    logger.info(f'js免嗅耗时:{get_interval(t1)}毫秒,播放地址:{play_url}')
H
hjdhnx 已提交
1475 1476 1477 1478
                    if not play_url and play_url!='' and play_url!={}:
                        play_url = origin_play_url
                    # if play_url == {}:
                    #     play_url = None
H
hjdhnx 已提交
1479 1480
            except Exception as e:
                logger.info(f'免嗅耗时:{get_interval(t1)}毫秒,并发生错误:{e}')
H
hjdhnx 已提交
1481
            # return play_url
H
hjdhnx 已提交
1482 1483
        else:
            logger.info(f'播放重定向到:{play_url}')
H
hjdhnx 已提交
1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496
            # return play_url

        if self.play_json:
            # 如果传了 play_json 参数并且是个大于0的列表的话
            if isinstance(self.play_json,list) and len(self.play_json) > 0:
                # 获取播放链接
                web_url = play_url if isinstance(play_url,str) else play_url.get('url')
                for pjson in self.play_json:
                    if pjson.get('re') and (pjson['re']=='*' or re.search(pjson['re'],web_url,re.S|re.M)):
                        if pjson.get('json') and isinstance(pjson['json'], dict):
                            if isinstance(play_url, str):
                                base_json = pjson['json']
                                base_json['url'] = web_url
H
hjdhnx 已提交
1497
                                play_url = base_json
H
hjdhnx 已提交
1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517
                            elif isinstance(play_url, dict):
                                base_json = pjson['json']
                                play_url.update(base_json)

                            # 不管有没有效,匹配到了就跑??? (当然不行了,要不然写来干嘛)
                            break

            else: # 没有指定列表默认表示需要解析,解析播放 (如果不要解析,我想也是没人会去写这个参数)
                base_json = {
                    'jx':1,  # 解析开
                    'parse':1, # 嗅探 关  pluto这个标识有问题 只好双1了
                }
                if isinstance(play_url,str):
                    base_json['url'] = play_url
                    play_url = base_json
                elif isinstance(play_url,dict):
                    play_url.update(base_json)

        logger.info(f'最终返回play_url:{play_url}')
        return play_url
H
hjdhnx 已提交
1518 1519 1520 1521 1522 1523 1524 1525 1526

if __name__ == '__main__':
    print(urljoin('https://api.web.360kan.com/v1/f',
                  '//0img.hitv.com/preview/sp_images/2022/01/28/202201281528074643023.jpg'))
    # exit()
    from utils import parser
    # js_path = f'js/玩偶姐姐.js'
    # js_path = f'js/555影视.js'
    with open('../js/模板.js', encoding='utf-8') as f:
H
hjdhnx 已提交
1527
        before = f.read().split('export')[0]
H
hjdhnx 已提交
1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545
    js_path = f'js/360影视.js'
    ctx, js_code = parser.runJs(js_path,before=before)
    ruleDict = ctx.rule.to_dict()
    # lazy = ctx.eval('lazy')
    # print(lazy)
    # ruleDict['id'] = rule  # 把路由请求的id装到字典里,后面播放嗅探才能用

    cms = CMS(ruleDict)
    print(cms.title)
    print(cms.homeContent())
    # print(cms.categoryContent('5',1))
    # print(cms.categoryContent('latest',1))
    # print(cms.detailContent(['https://www.2345ka.com/v/45499.html']))
    # print(cms.detailContent(1,['https://cokemv.me/voddetail/40573.html']))
    # cms.categoryContent('dianying',1)
    # print(cms.detailContent(['67391']))
    # print(cms.searchContent('斗罗大陆'))
    print(cms.searchContent('独行月球'))