cms.py 35.6 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

H
hjdhnx 已提交
7
import requests
8
import re
9
import math
H
hjdhnx 已提交
10
from utils.web import *
H
hjdhnx 已提交
11
from models import *
H
hjdhnx 已提交
12
from utils.config import playerConfig
H
hjdhnx 已提交
13
from utils.log import logger
14
from utils.encode import base64Encode,baseDecode,fetch,post,request,getCryptoJS,getPreJs,buildUrl,getHome
H
hjdhnx 已提交
15
from utils.encode import verifyCode,setDetail,join,urljoin2
H
hjdhnx 已提交
16
from utils.safePython import safePython
17
from utils.parser import runPy,runJScode,JsObjectWrapper
H
hjdhnx 已提交
18
from utils.htmlParser import jsoup
H
hjdhnx 已提交
19
from urllib.parse import urljoin
20
from concurrent.futures import ThreadPoolExecutor  # 引入线程池
H
hjdhnx 已提交
21
from flask import url_for,redirect
22
from easydict import EasyDict as edict
H
hjdhnx 已提交
23

H
hjdhnx 已提交
24 25
py_ctx = {
'requests':requests,'print':print,'base64Encode':base64Encode,'baseDecode':baseDecode,
H
hjdhnx 已提交
26
'log':logger.info,'fetch':fetch,'post':post,'request':request,'getCryptoJS':getCryptoJS,
H
hjdhnx 已提交
27
'buildUrl':buildUrl,'getHome':getHome,'setDetail':setDetail,'join':join,'urljoin2':urljoin2
H
hjdhnx 已提交
28
}
29
# print(getCryptoJS())
H
hjdhnx 已提交
30

H
hjdhnx 已提交
31
class CMS:
H
hjdhnx 已提交
32
    def __init__(self, rule, db=None, RuleClass=None, PlayParse=None,new_conf=None):
H
hjdhnx 已提交
33 34
        if new_conf is None:
            new_conf = {}
H
hjdhnx 已提交
35
        self.title = rule.get('title', '')
H
hjdhnx 已提交
36
        self.id = rule.get('id', self.title)
H
hjdhnx 已提交
37
        self.lazy = rule.get('lazy', False)
38
        self.play_disable = new_conf.get('PLAY_DISABLE',False)
39
        self.retry_count = new_conf.get('RETRY_CNT',3)
40
        self.lazy_mode = new_conf.get('LAZYPARSE_MODE')
41
        self.ocr_api = new_conf.get('OCR_API')
H
hjdhnx 已提交
42
        self.cate_exclude = new_conf.get('CATE_EXCLUDE','')
43 44 45 46
        try:
            self.vod = redirect(url_for('vod')).headers['Location']
        except:
            self.vod = '/vod'
H
hjdhnx 已提交
47
        # if not self.play_disable and self.lazy:
48 49
        if not self.play_disable:
            self.play_parse = rule.get('play_parse', False)
50 51 52 53
            try:
                play_url = getHost(self.lazy_mode)
            except:
                play_url = getHost(1,5705)
54
            # play_url = new_conf.get('PLAY_URL',getHost(2))
55 56 57
            if not play_url.startswith('http'):
                play_url = 'http://'+play_url
            if self.play_parse:
H
hjdhnx 已提交
58
                # self.play_url = play_url + self.vod + '?play_url='
H
hjdhnx 已提交
59
                self.play_url = f'{play_url}{self.vod}?rule={self.id}&play_url='
H
hjdhnx 已提交
60
                # logger.info(f'cms重定向链接:{self.play_url}')
61 62
            else:
                self.play_url = ''
H
hjdhnx 已提交
63
        else:
64
            self.play_parse = False
H
hjdhnx 已提交
65
            self.play_url = ''
H
hjdhnx 已提交
66
        # logger.info('播放免嗅地址: '+self.play_url)
67

H
hjdhnx 已提交
68 69
        self.db = db
        self.RuleClass = RuleClass
H
hjdhnx 已提交
70
        self.PlayParse = PlayParse
71
        host = rule.get('host','').rstrip('/')
72
        timeout = rule.get('timeout',5000)
H
hjdhnx 已提交
73
        homeUrl = rule.get('homeUrl','/')
74 75 76
        url = rule.get('url','')
        detailUrl = rule.get('detailUrl','')
        searchUrl = rule.get('searchUrl','')
H
hjdhnx 已提交
77 78 79 80
        default_headers = getHeaders(host)
        self_headers = rule.get('headers',{})
        default_headers.update(self_headers)
        headers = default_headers
81 82 83 84
        cookie = self.getCookie()
        # print(f'{self.title}cookie:{cookie}')
        if cookie:
            headers['cookie'] = cookie
85
        limit = rule.get('limit',6)
H
hjdhnx 已提交
86
        encoding = rule.get('编码', 'utf-8')
H
hjdhnx 已提交
87
        self.limit = min(limit,30)
88 89 90 91 92 93 94 95
        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
H
hjdhnx 已提交
96 97
                elif v == 'UC_UA':
                    headers[k] = UC_UA
98 99 100
        lower_keys = list(map(lambda x:x.lower(),keys))
        if not 'user-agent' in lower_keys:
            headers['User-Agent'] = UA
101 102
        if not 'referer' in lower_keys:
            headers['Referer'] = host
H
hjdhnx 已提交
103
        # print(headers)
104 105 106 107 108 109 110
        self.headers = headers
        self.host = host
        self.homeUrl = urljoin(host,homeUrl) if host and homeUrl else homeUrl
        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
H
hjdhnx 已提交
111
        else:
112 113 114 115
            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
H
hjdhnx 已提交
116 117
        self.class_name = rule.get('class_name','')
        self.class_url = rule.get('class_url','')
118
        self.class_parse = rule.get('class_parse','')
H
hjdhnx 已提交
119 120 121
        self.filter_name = rule.get('filter_name', '')
        self.filter_url = rule.get('filter_url', '')
        self.filter_parse = rule.get('filter_parse', '')
122
        self.double = rule.get('double',False)
H
hjdhnx 已提交
123 124 125
        self.一级 = rule.get('一级','')
        self.二级 = rule.get('二级','')
        self.搜索 = rule.get('搜索','')
126
        self.推荐 = rule.get('推荐','')
H
hjdhnx 已提交
127
        self.encoding = encoding
128
        self.timeout = round(int(timeout)/1000,2)
H
hjdhnx 已提交
129 130
        self.filter = rule.get('filter',[])
        self.extend = rule.get('extend',[])
131
        self.d = self.getObject()
H
hjdhnx 已提交
132 133 134 135

    def getName(self):
        return self.title

136 137 138 139 140 141 142 143 144 145 146 147
    def getObject(self):
        o = edict({
            'jsp':jsoup(self.url),
            'getParse':self.getParse,
            'saveParse':self.saveParse,
            'headers':self.headers,
            'encoding':self.encoding,
            'name':self.title,
            'timeout':self.timeout,
        })
        return o

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
    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": "",
            "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
H
hjdhnx 已提交
189 190 191 192
        pjfh = jsp.pjfh
        pjfa = jsp.pjfa
        pj = jsp.pj

193 194 195
        pq = jsp.pq
        return pdfh,pdfa,pd,pq

H
hjdhnx 已提交
196 197 198 199 200 201 202 203 204 205 206
    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:
207 208
            if not all([res.class_name,res.class_url]):
                return []
H
hjdhnx 已提交
209 210 211 212
            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)
H
hjdhnx 已提交
213
            logger.info(f"{self.getName()}使用缓存分类:{classes}")
H
hjdhnx 已提交
214 215 216 217
            return classes
        else:
            return []

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

H
hjdhnx 已提交
249 250 251 252 253 254 255 256 257 258 259 260
    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()
H
hjdhnx 已提交
261
        # print(res)
H
hjdhnx 已提交
262 263 264 265
        if res:
            res.class_name = class_name
            res.class_url = class_url
            self.db.session.add(res)
H
hjdhnx 已提交
266
            msg = f'{self.getName()}修改成功:{res.id}'
H
hjdhnx 已提交
267 268 269 270
        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()
H
hjdhnx 已提交
271
            msg = f'{self.getName()}新增成功:{res.id}'
H
hjdhnx 已提交
272 273 274

        try:
            self.db.session.commit()
H
hjdhnx 已提交
275
            logger.info(msg)
H
hjdhnx 已提交
276 277 278
        except Exception as e:
            return f'发生了错误:{e}'

H
hjdhnx 已提交
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
    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:
H
hjdhnx 已提交
294
            return ''
H
hjdhnx 已提交
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

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

H
hjdhnx 已提交
323

324
    def homeContent(self,fypage=1):
H
hjdhnx 已提交
325 326
        # yanaifei
        # https://yanetflix.com/vodtype/dianying.html
H
hjdhnx 已提交
327
        t1 = time()
H
hjdhnx 已提交
328 329
        result = {}
        classes = []
330
        video_result = self.blank()
331 332 333 334 335 336 337 338 339 340 341

        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)
H
hjdhnx 已提交
342
        print(self.headers)
H
hjdhnx 已提交
343
        has_cache = False
344
        if self.homeUrl.startswith('http'):
345 346 347
            # print(self.homeUrl)
            # print(self.class_parse)
            try:
H
hjdhnx 已提交
348
                if self.class_parse:
H
hjdhnx 已提交
349
                    t2 = time()
H
hjdhnx 已提交
350
                    cache_classes = self.getClasses()
H
hjdhnx 已提交
351
                    logger.info(f'{self.getName()}读取缓存耗时:{get_interval(t2)}毫秒')
H
hjdhnx 已提交
352 353
                    if len(cache_classes) > 0:
                        classes = cache_classes
H
hjdhnx 已提交
354
                        # print(cache_classes)
H
hjdhnx 已提交
355
                        has_cache = True
H
hjdhnx 已提交
356 357 358 359 360 361 362 363
                # 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)
                    r.encoding = self.encoding
                    html = r.text
H
hjdhnx 已提交
364
                    # print(html)
H
hjdhnx 已提交
365
                    # print(self.headers)
H
hjdhnx 已提交
366 367
                    if self.class_parse and not has_cache:
                        p = self.class_parse.split(';')
368
                        # print(p)
H
hjdhnx 已提交
369 370 371 372 373
                        jsp = jsoup(self.url)
                        pdfh = jsp.pdfh
                        pdfa = jsp.pdfa
                        pd = jsp.pd
                        items = pdfa(html,p[0])
374 375
                        # print(len(items))
                        # print(items)
H
hjdhnx 已提交
376 377
                        for item in items:
                            title = pdfh(item, p[1])
H
hjdhnx 已提交
378 379 380
                            # 过滤排除掉标题名称
                            if self.cate_exclude and jsp.test(self.cate_exclude, title):
                                continue
H
hjdhnx 已提交
381
                            url = pd(item, p[2])
382
                            # print(url)
H
hjdhnx 已提交
383 384 385 386 387 388 389 390 391 392 393
                            tag = url
                            if len(p) > 3 and p[3].strip():
                                tag = self.regexp(p[3].strip(),url,0)
                            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)
394
            except Exception as e:
H
hjdhnx 已提交
395
                logger.info(f'{self.getName()}主页发生错误:{e}')
396

H
hjdhnx 已提交
397 398
        result['class'] = classes
        if self.filter:
H
hjdhnx 已提交
399
            result['filters'] = playerConfig['filter']
400
        result.update(video_result)
H
hjdhnx 已提交
401
        # print(result)
H
hjdhnx 已提交
402
        logger.info(f'{self.getName()}获取首页总耗时(包含读取缓存):{get_interval(t1)}毫秒')
H
hjdhnx 已提交
403 404
        return result

405 406 407 408 409 410 411 412 413 414 415 416
    def homeVideoContent(self,html,fypage=1):
        if not self.推荐:
            return self.blank()

        p = self.推荐.split(';')  # 解析
        if not self.double and len(p) < 5:
            return self.blank()
        if self.double and len(p) < 6:
            return self.blank()
        result = {}
        videos = []
        jsp = jsoup(self.homeUrl)
H
hjdhnx 已提交
417 418 419 420
        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
H
hjdhnx 已提交
421
        # print(html)
422 423 424 425 426 427
        try:
            if self.double:
                items = pdfa(html, p[0])
                for item in items:
                    items2 = pdfa(item,p[1])
                    for item2 in items2:
428 429 430 431
                        try:
                            title = pdfh(item2, p[2])
                            img = pd(item2, p[3])
                            desc = pdfh(item2, p[4])
H
hjdhnx 已提交
432
                            links = [pd(item2, p5) if not self.detailUrl else pdfh(item2, p5) for p5 in p[5].split('+')]
H
hjdhnx 已提交
433
                            link = '$'.join(links)
434 435 436 437 438 439 440 441 442 443 444 445 446
                            content = '' if len(p) < 7 else pdfh(item2, p[6])
                            videos.append({
                                "vod_id": link,
                                "vod_name": title,
                                "vod_pic": img,
                                "vod_remarks": desc,
                                "vod_content": content,
                                "type_id": 1,
                                "type_name": "首页推荐",
                            })
                        except:
                            pass
            else:
H
hjdhnx 已提交
447 448
                items = pdfa(html, p[0].replace('json:',''))
                # print(items)
449 450 451 452 453
                for item in items:
                    try:
                        title = pdfh(item, p[1])
                        img = pd(item, p[2])
                        desc = pdfh(item, p[3])
H
hjdhnx 已提交
454 455 456
                        # link = pd(item, p[4])
                        links = [pd(item, p5) if not self.detailUrl else pdfh(item, p5) for p5 in p[4].split('+')]
                        link = '$'.join(links)
457
                        content = '' if len(p) < 6 else pdfh(item, p[5])
458 459 460 461 462 463 464 465 466
                        videos.append({
                            "vod_id": link,
                            "vod_name": title,
                            "vod_pic": img,
                            "vod_remarks": desc,
                            "vod_content": content,
                            "type_id": 1,
                            "type_name": "首页推荐",
                        })
467 468
                    except:
                        pass
H
hjdhnx 已提交
469
            result['list'] = videos[min((fypage-1)*self.limit,len(videos)-1):min(fypage*self.limit,len(videos))]
470 471 472 473 474 475
            result['code'] = 1
            result['msg'] = '数据列表'
            result['page'] = fypage
            result['pagecount'] = math.ceil(len(videos)/self.limit)
            result['limit'] = self.limit
            result['total'] = len(videos)
H
hjdhnx 已提交
476
            result['now_count'] = len(result['list'])
477 478
            return result
        except Exception as e:
H
hjdhnx 已提交
479
            logger.info(f'首页内容获取失败:{e}')
480
            return self.blank()
H
hjdhnx 已提交
481 482 483 484 485 486 487 488

    def categoryContent(self, fyclass, fypage):
        """
        一级带分类的数据返回
        :param fyclass: 分类标识
        :param fypage: 页码
        :return: cms一级数据
        """
H
hjdhnx 已提交
489
        
H
hjdhnx 已提交
490 491 492 493 494 495 496 497 498
        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)
H
hjdhnx 已提交
499 500
        # url = self.url + '/{0}.html'.format
        t1 = time()
H
hjdhnx 已提交
501 502
        pg = str(fypage)
        url = self.url.replace('fyclass',fyclass).replace('fypage',pg)
503 504
        if fypage == 1 and self.test('[\[\]]',url):
            url = url.split('[')[1].split(']')[0]
H
hjdhnx 已提交
505
        p = self.一级.split(';')  # 解析
506 507 508
        if len(p) < 5:
            return self.blank()

H
hjdhnx 已提交
509
        jsp = jsoup(self.url)
H
hjdhnx 已提交
510 511 512 513
        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
H
hjdhnx 已提交
514 515 516
        # 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'))
517

H
hjdhnx 已提交
518
        videos = []
519 520 521 522 523
        items = []
        try:
            r = requests.get(url, headers=self.headers, timeout=self.timeout)
            r.encoding = self.encoding
            print(r.url)
H
hjdhnx 已提交
524 525
            # html = r.text
            html = r.json() if is_json else r.text
H
hjdhnx 已提交
526
            # print(html)
H
hjdhnx 已提交
527
            items = pdfa(html,p[0].replace('json:','',1))
528 529
        except:
            pass
H
hjdhnx 已提交
530
        # print(items)
H
hjdhnx 已提交
531 532
        for item in items:
            # print(item)
533 534 535 536
            try:
                title = pdfh(item, p[1])
                img = pd(item, p[2])
                desc = pdfh(item, p[3])
H
hjdhnx 已提交
537 538
                links = [pd(item, p4) if not self.detailUrl else pdfh(item, p4) for p4 in p[4].split('+')]
                link = '$'.join(links)
539 540 541
                content = '' if len(p) < 6 else pdfh(item, p[5])
                # sid = self.regStr(sid, "/video/(\\S+).html")
                videos.append({
H
hjdhnx 已提交
542
                    "vod_id": f'{fyclass}${link}' if self.detailUrl else link,# 分类,播放链接
543 544 545 546 547
                    "vod_name": title,
                    "vod_pic": img,
                    "vod_remarks": desc,
                    "vod_content": content,
                })
H
hjdhnx 已提交
548 549
            except Exception as e:
                print(f'发生了错误:{e}')
550
                pass
H
hjdhnx 已提交
551
        result['list'] = videos
H
hjdhnx 已提交
552
        result['page'] = fypage
H
hjdhnx 已提交
553
        result['pagecount'] = 9999
554
        result['limit'] = 9999
H
hjdhnx 已提交
555
        result['total'] = 999999
H
hjdhnx 已提交
556
        logger.info(f'{self.getName()}获取分类{fyclass}{fypage}页耗时:{get_interval(t1)}毫秒,共计{round(len(str(result)) / 1000, 2)} kb')
H
hjdhnx 已提交
557
        
H
hjdhnx 已提交
558 559
        return result

H
hjdhnx 已提交
560
    def detailOneVod(self,id,fyclass=''):
561 562
        detailUrl = str(id)
        vod = {}
563
        if not detailUrl.startswith('http'):
H
hjdhnx 已提交
564
            url = self.detailUrl.replace('fyid', detailUrl).replace('fyclass',fyclass)
H
hjdhnx 已提交
565
        else:
566
            url = detailUrl
567
        # print(url)
H
hjdhnx 已提交
568 569 570 571 572
        try:
            p = self.二级  # 解析
            if p == '*':
                vod = self.blank_vod()
                vod['vod_play_from'] = '道长在线'
H
hjdhnx 已提交
573
                vod['vod_remarks'] = self.play_url+detailUrl
H
hjdhnx 已提交
574
                vod['vod_actor'] = '没有二级,只有一级链接直接嗅探播放'
H
hjdhnx 已提交
575
                vod['vod_content'] = detailUrl
H
hjdhnx 已提交
576 577 578
                vod['vod_play_url'] = '嗅探播放$'+detailUrl
                return vod

H
hjdhnx 已提交
579
            if not isinstance(p,dict) and not isinstance(p,str) and not str(p).startswith('js:'):
H
hjdhnx 已提交
580 581 582
                return vod

            jsp = jsoup(self.url)
H
hjdhnx 已提交
583

H
hjdhnx 已提交
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
            is_json = p.get('is_json',False) if isinstance(p,dict) else False # 二级里加is_json参数
            is_js = isinstance(p,str) and str(p).startswith('js:') # 是js
            if is_js:
                headers['Referer'] = getHome(url)
                py_ctx.update({
                    'input': url,
                    'fetch_params': {'headers': headers, 'timeout': self.d.timeout, 'encoding': self.d.encoding},
                    'd': self.d,
                    'getParse': self.d.getParse,
                    'saveParse': self.d.saveParse,
                    'jsp':jsp,'setDetail':setDetail,
                })
                ctx = py_ctx
                # print(ctx)
                jscode = getPreJs() + p.replace('js:','',1)
                # print(jscode)
                loader, _ = runJScode(jscode, ctx=ctx)
                # print(loader.toString())
                vod = loader.eval('vod')
                if isinstance(vod,JsObjectWrapper):
                    vod = vod.to_dict()
                else:
                    vod = {}
                # print(type(vod))
                # print(vod)
H
hjdhnx 已提交
609
            else:
H
hjdhnx 已提交
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
                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
                obj = {}
                vod_name = ''
                r = requests.get(url, headers=self.headers, timeout=self.timeout)
                r.encoding = self.encoding
                # html = r.text
                html = r.json() if is_json else r.text
                # print(html)
                if p.get('title'):
                    p1 = p['title'].split(';')
                    vod_name = pdfh(html,p1[0]).replace('\n',' ')
                    # title = '\n'.join([pdfh(html,i).replace('\n',' ') for i in p1])
                    title = '\n'.join([','.join([pdfh(html, pp1).strip() for pp1 in i.split('+')]) for i in p1])
                    # print(title)
                    obj['title'] = title
                if p.get('desc'):
                    p1 = p['desc'].split(';')
                    desc = '\n'.join([pdfh(html,i).replace('\n',' ') for i in p1])
                    obj['desc'] = desc

                if p.get('content'):
                    p1 = p['content'].split(';')
                    content = '\n'.join([pdfh(html,i).replace('\n',' ') for i in p1])
                    obj['content'] = content

                if p.get('img'):
                    p1 = p['img'].split(';')
                    img = '\n'.join([pdfh(html,i).replace('\n',' ') for i in p1])
                    obj['img'] = img

                vod = {
                    "vod_id": detailUrl,
                    "vod_name": vod_name,
                    "vod_pic": obj.get('img',''),
                    "type_name": obj.get('title',''),
                    "vod_year": "",
                    "vod_area": "",
                    "vod_remarks": obj.get('desc',''),
                    "vod_actor": "",
                    "vod_director": "",
                    "vod_content": obj.get('content','')
                }

                vod_play_from = '$$$'
                playFrom = []
                if p.get('tabs'):
H
hjdhnx 已提交
659
                    # print(p['tabs'].split(';')[0])
H
hjdhnx 已提交
660 661 662 663 664 665 666 667
                    vodHeader = pdfa(html,p['tabs'].split(';')[0])
                    # print(f'线路列表数:{len((vodHeader))}')
                    # print(vodHeader)
                    if not is_json:
                        vodHeader = [pq(v).text() for v in vodHeader]
                else:
                    vodHeader = ['道长在线']

H
hjdhnx 已提交
668 669
                # print(vodHeader)

H
hjdhnx 已提交
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
                for v in vodHeader:
                    playFrom.append(v)
                vod_play_from = vod_play_from.join(playFrom)

                vod_play_url = '$$$'
                vod_tab_list = []
                if p.get('lists'):
                    for i in range(len(vodHeader)):
                       tab_name = str(vodHeader[i])
                       tab_ext = p['tabs'].split(';')[1] if len(p['tabs'].split(';')) > 1 else ''
                       p1 = p['lists'].replace('#idv',tab_name).replace('#id',str(i))
                       tab_ext = tab_ext.replace('#idv',tab_name).replace('#id',str(i))
                       vodList = pdfa(html,p1) # 1条线路的选集列表
                       # print(vodList)
                       # vodList = [pq(i).text()+'$'+pd(i,'a&&href') for i in vodList]  # 拼接成 名称$链接
                       if self.play_parse: # 自动base64编码
                           vodList = [(pdfh(html,tab_ext) if tab_ext else tab_name)+'$'+self.play_url+base64Encode(i) for i in vodList] if is_json else\
                               [pq(i).text()+'$'+self.play_url+base64Encode(pd(i,'a&&href')) for i in vodList]  # 拼接成 名称$链接
                       else:
                           vodList = [(pdfh(html, tab_ext) if tab_ext else tab_name) + '$' + self.play_url + i for i in
                                      vodList] if is_json else \
                               [pq(i).text() + '$' + self.play_url + pd(i, 'a&&href') for i in vodList]  # 拼接成 名称$链接
                       vlist = '#'.join(vodList) # 拼多个选集
                       vod_tab_list.append(vlist)
                    vod_play_url = vod_play_url.join(vod_tab_list)
                # print(vod_play_url)
                vod['vod_play_from'] = vod_play_from
H
hjdhnx 已提交
697
                # print(vod_play_from)
H
hjdhnx 已提交
698
                vod['vod_play_url'] = vod_play_url
H
hjdhnx 已提交
699
                # print(vod_play_url)
H
hjdhnx 已提交
700
        except Exception as e:
701
            logger.info(f'{self.getName()}获取单个详情页{detailUrl}出错{e}')
H
hjdhnx 已提交
702
        # print(vod)
703 704 705 706 707 708 709 710
        return vod

    def detailContent(self, fypage, array):
        """
        cms二级数据
        :param array:
        :return:
        """
H
hjdhnx 已提交
711
        t1 = time()
H
hjdhnx 已提交
712
        array = array if len(array) <= self.limit else array[(fypage-1)*self.limit:min(self.limit*fypage,len(array))]
713 714
        thread_pool = ThreadPoolExecutor(min(self.limit,len(array)))  # 定义线程池来启动多线程执行此任务
        obj_list = []
H
hjdhnx 已提交
715 716
        try:
            for vod_url in array:
H
hjdhnx 已提交
717
                # print(vod_url)
H
hjdhnx 已提交
718 719 720 721 722 723
                vod_class = ''
                if vod_url.find('$') > -1:
                    tmp = vod_url.split('$')
                    vod_class = tmp[0]
                    vod_url = tmp[1]
                obj = thread_pool.submit(self.detailOneVod, vod_url,vod_class)
H
hjdhnx 已提交
724 725 726 727 728 729 730 731 732 733 734 735
                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 已提交
736
        # print(result)
H
hjdhnx 已提交
737 738
        return result

H
hjdhnx 已提交
739
    def searchContent(self, key, fypage=1):
H
hjdhnx 已提交
740
        pg = str(fypage)
741 742
        if not self.searchUrl:
            return self.blank()
H
hjdhnx 已提交
743
        url = self.searchUrl.replace('**', key).replace('fypage',pg)
H
hjdhnx 已提交
744
        logger.info(f'{self.getName()}搜索链接:{url}')
745 746 747 748 749
        if not self.搜索:
            return self.blank()
        p = self.一级.split(';') if self.搜索 == '*' and self.一级 else self.搜索.split(';')  # 解析
        if len(p) < 5:
            return self.blank()
H
hjdhnx 已提交
750
        jsp = jsoup(self.url)
H
hjdhnx 已提交
751 752 753 754
        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
H
hjdhnx 已提交
755 756
        pq = jsp.pq
        videos = []
H
hjdhnx 已提交
757
        try:
758
            r = requests.get(url, headers=self.headers,timeout=self.timeout)
H
hjdhnx 已提交
759
            r.encoding = self.encoding
H
hjdhnx 已提交
760 761
            # html = r.text
            html = r.json() if is_json else r.text
762
            # print(html)
H
hjdhnx 已提交
763
            if not is_json and html.find('输入验证码') > -1:
764
                cookie = verifyCode(url,self.headers,self.timeout,self.retry_count,self.ocr_api)
765
                # cookie = ''
766 767 768 769 770 771 772 773 774 775
                if not cookie:
                    return {
                        'list': videos
                    }
                self.saveCookie(cookie)
                self.headers['cookie'] = cookie
                r = requests.get(url, headers=self.headers, timeout=self.timeout)
                r.encoding = self.encoding
                html = r.text

H
hjdhnx 已提交
776
            items = pdfa(html,p[0].replace('json:','',1))
H
hjdhnx 已提交
777
            print(items)
H
hjdhnx 已提交
778 779 780
            videos = []
            for item in items:
                # print(item)
781 782 783 784
                try:
                    title = pdfh(item, p[1])
                    img = pd(item, p[2])
                    desc = pdfh(item, p[3])
H
hjdhnx 已提交
785 786 787
                    # link = '$'.join([pd(item, p4) for p4 in p[4].split('+')])
                    links = [pd(item, p4) if not self.detailUrl else pdfh(item, p4) for p4 in p[4].split('+')]
                    link = '$'.join(links)
788 789 790 791 792 793 794 795 796 797 798 799
                    content = '' if len(p) < 6 else pdfh(item, p[5])
                    # sid = self.regStr(sid, "/video/(\\S+).html")
                    videos.append({
                        "vod_id": link,
                        "vod_name": title,
                        "vod_pic": img,
                        "vod_remarks": desc,
                        "vod_content": content,
                    })
                except:
                    pass
            # print(videos)
H
hjdhnx 已提交
800 801
        except Exception as e:
            logger.info(f'搜索{self.getName()}发生错误:{e}')
H
hjdhnx 已提交
802 803 804 805 806
        result = {
            'list': videos
        }
        return result

H
hjdhnx 已提交
807
    def playContent(self, play_url,jxs=None,flag=None):
H
hjdhnx 已提交
808
        # logger.info('播放免嗅地址: ' + self.play_url)
H
hjdhnx 已提交
809 810
        if not jxs:
            jxs = []
H
hjdhnx 已提交
811 812 813 814
        try:
            play_url = baseDecode(play_url) # 自动base64解码
        except:
            pass
H
hjdhnx 已提交
815
        if self.lazy:
816
            print(f'{play_url}->开始执行免嗅代码{type(self.lazy)}->{self.lazy}')
H
hjdhnx 已提交
817 818
            t1 = time()
            try:
819 820 821 822
                if type(self.lazy) == JsObjectWrapper:
                    logger.info(f'lazy非纯文本免嗅失败耗时:{get_interval(t1)}毫秒,播放地址:{play_url}')

                elif not str(self.lazy).startswith('js:'):
H
hjdhnx 已提交
823 824 825 826 827 828 829 830 831 832 833 834 835 836 837
                    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:
                    jscode = str(self.lazy).split('js:')[1]
                    # jscode = f'var input={play_url};{jscode}'
                    # print(jscode)
838
                    headers['Referer'] = getHome(play_url)
H
hjdhnx 已提交
839 840
                    py_ctx.update({
                        'input': play_url,
841
                        'fetch_params':{'headers':headers,'timeout':self.d.timeout,'encoding':self.d.encoding},
H
hjdhnx 已提交
842 843
                        'd': self.d,
                        'jxs':jxs,
844 845
                        'getParse':self.d.getParse,
                        'saveParse':self.d.saveParse,
H
hjdhnx 已提交
846 847 848 849 850 851 852 853 854 855
                        'pdfh': self.d.jsp.pdfh,
                        'pdfa': self.d.jsp.pdfa, 'pd': self.d.jsp.pd,
                    })
                    ctx = py_ctx
                    # print(ctx)
                    jscode = getPreJs() + jscode
                    # print(jscode)
                    loader,_ = runJScode(jscode,ctx=ctx)
                    # print(loader.toString())
                    play_url = loader.eval('input')
H
hjdhnx 已提交
856 857 858 859
                    if isinstance(play_url,JsObjectWrapper):
                        play_url = play_url.to_dict()
                    # print(type(play_url))
                    # print(play_url)
H
hjdhnx 已提交
860 861 862
                    logger.info(f'js免嗅耗时:{get_interval(t1)}毫秒,播放地址:{play_url}')
            except Exception as e:
                logger.info(f'免嗅耗时:{get_interval(t1)}毫秒,并发生错误:{e}')
H
hjdhnx 已提交
863 864 865 866 867
            return play_url
        else:
            logger.info(f'播放重定向到:{play_url}')
            return play_url

H
hjdhnx 已提交
868
if __name__ == '__main__':
H
hjdhnx 已提交
869 870 871
    print(urljoin('https://api.web.360kan.com/v1/f',
                  '//0img.hitv.com/preview/sp_images/2022/01/28/202201281528074643023.jpg'))
    # exit()
H
hjdhnx 已提交
872
    from utils import parser
H
hjdhnx 已提交
873
    # js_path = f'js/玩偶姐姐.js'
H
hjdhnx 已提交
874
    # js_path = f'js/555影视.js'
875 876
    with open('../js/模板.js', encoding='utf-8') as f:
        before = f.read()
H
hjdhnx 已提交
877
    js_path = f'js/360影视.js'
878 879
    ctx, js_code = parser.runJs(js_path,before=before)
    ruleDict = ctx.rule.to_dict()
880 881
    # lazy = ctx.eval('lazy')
    # print(lazy)
882 883 884
    # ruleDict['id'] = rule  # 把路由请求的id装到字典里,后面播放嗅探才能用

    cms = CMS(ruleDict)
H
hjdhnx 已提交
885
    print(cms.title)
H
hjdhnx 已提交
886
    print(cms.homeContent())
H
hjdhnx 已提交
887
    # print(cms.categoryContent('5',1))
888
    # print(cms.categoryContent('latest',1))
H
hjdhnx 已提交
889
    # print(cms.detailContent(['https://www.2345ka.com/v/45499.html']))
H
hjdhnx 已提交
890
    # print(cms.detailContent(1,['https://cokemv.me/voddetail/40573.html']))
H
hjdhnx 已提交
891
    # cms.categoryContent('dianying',1)
H
hjdhnx 已提交
892
    # print(cms.detailContent(['67391']))
H
hjdhnx 已提交
893 894
    # print(cms.searchContent('斗罗大陆'))
    print(cms.searchContent('独行月球'))