cms.py 15.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 requests
7
import re
8
import math
H
hjdhnx 已提交
9
from utils.web import *
H
hjdhnx 已提交
10 11
from utils.config import config
from utils.htmlParser import jsoup
H
hjdhnx 已提交
12
from urllib.parse import urljoin
13
from concurrent.futures import ThreadPoolExecutor  # 引入线程池
H
hjdhnx 已提交
14 15 16

class CMS:
    def __init__(self,rule):
17
        host = rule.get('host','').rstrip('/')
18
        timeout = rule.get('timeout',5000)
H
hjdhnx 已提交
19
        homeUrl = rule.get('homeUrl','/')
20 21 22 23
        url = rule.get('url','')
        detailUrl = rule.get('detailUrl','')
        searchUrl = rule.get('searchUrl','')
        headers = rule.get('headers',{})
24
        limit = rule.get('limit',6)
H
hjdhnx 已提交
25
        encoding = rule.get('编码', 'utf-8')
26
        self.limit = min(limit,20)
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
        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
        lower_keys = list(map(lambda x:x.lower(),keys))
        if not 'user-agent' in lower_keys:
            headers['User-Agent'] = UA
        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 已提交
45
        else:
46 47 48 49
            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 已提交
50 51
        self.class_name = rule.get('class_name','')
        self.class_url = rule.get('class_url','')
52
        self.class_parse = rule.get('class_parse','')
53
        self.double = rule.get('double',False)
H
hjdhnx 已提交
54 55 56
        self.一级 = rule.get('一级','')
        self.二级 = rule.get('二级','')
        self.搜索 = rule.get('搜索','')
57
        self.推荐 = rule.get('推荐','')
H
hjdhnx 已提交
58
        self.title = rule.get('title','')
H
hjdhnx 已提交
59
        self.encoding = encoding
60
        self.timeout = round(int(timeout)/1000,2)
H
hjdhnx 已提交
61 62
        self.filter = rule.get('filter',[])
        self.extend = rule.get('extend',[])
H
hjdhnx 已提交
63 64 65 66

    def getName(self):
        return self.title

67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
    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
        pq = jsp.pq
        return pdfh,pdfa,pd,pq

111
    def homeContent(self,fypage=1):
H
hjdhnx 已提交
112 113 114 115
        # yanaifei
        # https://yanetflix.com/vodtype/dianying.html
        result = {}
        classes = []
116
        video_result = self.blank()
117 118 119 120 121 122 123 124 125 126 127

        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)
128
        if self.homeUrl.startswith('http'):
129 130 131 132
            # print(self.homeUrl)
            # print(self.class_parse)
            try:
                r = requests.get(self.homeUrl,headers=self.headers,timeout=self.timeout)
H
hjdhnx 已提交
133
                r.encoding = self.encoding
134
                html = r.text
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
                if self.class_parse:
                    p = self.class_parse.split(';')
                    jsp = jsoup(self.url)
                    pdfh = jsp.pdfh
                    pdfa = jsp.pdfa
                    pd = jsp.pd
                    items = pdfa(html,p[0])
                    for item in items:
                        title = pdfh(item, p[1])
                        url = pd(item, p[2])
                        tag = url
                        if len(p) > 3 and p[3].strip():
                            tag = self.regexp(p[3].strip(),url,0)
                        classes.append({
                            'type_name': title,
                            'type_id': tag
                        })

                video_result = self.homeVideoContent(html,fypage)
154 155 156
            except Exception as e:
                print(e)

H
hjdhnx 已提交
157 158 159
        result['class'] = classes
        if self.filter:
            result['filters'] = config['filter']
160
        result.update(video_result)
H
hjdhnx 已提交
161 162
        return result

163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
    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)
        pdfh = jsp.pdfh
        pdfa = jsp.pdfa
        pd = jsp.pd
        try:
            if self.double:
                items = pdfa(html, p[0])
                for item in items:
                    items2 = pdfa(item,p[1])
                    for item2 in items2:
                        title = pdfh(item2, p[2])
                        img = pd(item2, p[3])
                        desc = pdfh(item2, p[4])
                        link = pd(item2, p[5])
                        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": "首页推荐",
                        })
            else:
                items = pdfa(html, p[0])
                for item in items:
                    title = pdfh(item, p[1])
                    img = pd(item, p[2])
                    desc = pdfh(item, p[3])
                    link = pd(item, p[4])
                    content = '' if len(p) < 6 else pdfh(item, p[5])
                    videos.append({
                        "vod_id": link,
                        "vod_name": title,
                        "vod_pic": img,
                        "vod_remarks": desc,
                        "vod_content": content,
                        "type_id": 1,
                        "type_name": "首页推荐",
                    })
            result['list'] = videos
            result['code'] = 1
            result['msg'] = '数据列表'
            result['page'] = fypage
            result['pagecount'] = math.ceil(len(videos)/self.limit)
            result['limit'] = self.limit
            result['total'] = len(videos)
            return result
        except Exception as e:
            print(f'首页内容获取失败:{e}')
            return self.blank()
H
hjdhnx 已提交
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244

    def categoryContent(self, fyclass, fypage):
        """
        一级带分类的数据返回
        :param fyclass: 分类标识
        :param fypage: 页码
        :return: cms一级数据
        """

        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(params)
H
hjdhnx 已提交
245 246
        pg = str(fypage)
        url = self.url.replace('fyclass',fyclass).replace('fypage',pg)
247 248 249
        if fypage == 1 and self.test('[\[\]]',url):
            url = url.split('[')[1].split(']')[0]
        r = requests.get(url, headers=self.headers,timeout=self.timeout)
H
hjdhnx 已提交
250
        r.encoding = self.encoding
251
        print(r.url)
H
hjdhnx 已提交
252
        p = self.一级.split(';')  # 解析
253 254 255
        if len(p) < 5:
            return self.blank()

H
hjdhnx 已提交
256 257 258 259
        jsp = jsoup(self.url)
        pdfh = jsp.pdfh
        pdfa = jsp.pdfa
        pd = jsp.pd
H
hjdhnx 已提交
260 261 262
        # 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'))
H
hjdhnx 已提交
263 264 265 266 267 268 269 270
        items = pdfa(r.text, p[0])
        videos = []
        for item in items:
            # print(item)
            title = pdfh(item, p[1])
            img = pd(item, p[2])
            desc = pdfh(item, p[3])
            link = pd(item, p[4])
H
hjdhnx 已提交
271
            content = '' if len(p) < 6 else pdfh(item, p[5])
H
hjdhnx 已提交
272 273 274 275 276 277 278 279 280
            # sid = self.regStr(sid, "/video/(\\S+).html")
            videos.append({
                "vod_id": link,
                "vod_name": title,
                "vod_pic": img,
                "vod_remarks": desc,
                "vod_content": content,
            })
        result['list'] = videos
H
hjdhnx 已提交
281
        result['page'] = fypage
H
hjdhnx 已提交
282
        result['pagecount'] = 9999
283
        result['limit'] = 9999
H
hjdhnx 已提交
284 285 286
        result['total'] = 999999
        return result

287 288 289
    def detailOneVod(self,id):
        detailUrl = str(id)
        vod = {}
290 291
        if not detailUrl.startswith('http'):
            url = self.detailUrl.replace('fyid', detailUrl)
H
hjdhnx 已提交
292
        else:
293
            url = detailUrl
294
        # print(url)
295
        r = requests.get(url, headers=self.headers,timeout=self.timeout)
H
hjdhnx 已提交
296
        r.encoding = self.encoding
H
hjdhnx 已提交
297 298 299
        html = r.text
        # print(html)
        p = self.二级  # 解析
300 301 302 303 304 305 306
        if p == '*':
            vod = self.blank_vod()
            vod['vod_play_from'] = '道长在线'
            vod['desc'] = detailUrl
            vod['vod_actor'] = '没有二级,只有一级链接直接嗅探播放'
            vod['content'] = detailUrl
            vod['vod_play_url'] = '嗅探播放$'+detailUrl
307
            return vod
308 309

        if not isinstance(p,dict):
310
            return vod
311

H
hjdhnx 已提交
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
        jsp = jsoup(self.url)
        pdfh = jsp.pdfh
        pdfa = jsp.pdfa
        pd = jsp.pd
        pq = jsp.pq
        obj = {}
        vod_name = ''
        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])
            # 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 = {
341
            "vod_id": detailUrl,
H
hjdhnx 已提交
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
            "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'):
            vodHeader = pdfa(html,p['tabs'])
            vodHeader = [pq(v).text() for v in vodHeader]
        else:
            vodHeader = ['道长在线']

        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)):
               p1 = p['lists'].replace('#id',str(i))
               vodList = pdfa(html,p1) # 1条线路的选集列表
               vodList = [pq(i).text()+'$'+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
        vod['vod_play_url'] = vod_play_url

379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
        return vod

    def detailContent(self, fypage, array):
        """
        cms二级数据
        :param array:
        :return:
        """
        array = array[(fypage-1)*self.limit:min(self.limit*fypage,len(array))]
        thread_pool = ThreadPoolExecutor(min(self.limit,len(array)))  # 定义线程池来启动多线程执行此任务
        obj_list = []
        for vod_url in array:
            obj = thread_pool.submit(self.detailOneVod, vod_url)
            obj_list.append(obj)
        thread_pool.shutdown(wait=True)  # 等待所有子线程并行完毕
        vod_list = [obj.result() for obj in obj_list]
H
hjdhnx 已提交
395
        result = {
396
            'list': vod_list
H
hjdhnx 已提交
397 398 399
        }
        return result

H
hjdhnx 已提交
400
    def searchContent(self, key, fypage=1):
H
hjdhnx 已提交
401
        pg = str(fypage)
402 403
        if not self.searchUrl:
            return self.blank()
H
hjdhnx 已提交
404 405
        url = self.searchUrl.replace('**', key).replace('fypage',pg)
        print(url)
406
        r = requests.get(url, headers=self.headers)
H
hjdhnx 已提交
407
        r.encoding = self.encoding
H
hjdhnx 已提交
408
        html = r.text
409 410 411 412 413 414
        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 已提交
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
        jsp = jsoup(self.url)
        pdfh = jsp.pdfh
        pdfa = jsp.pdfa
        pd = jsp.pd
        pq = jsp.pq
        items = pdfa(html, p[0])
        videos = []
        for item in items:
            # print(item)
            title = pdfh(item, p[1])
            img = pd(item, p[2])
            desc = pdfh(item, p[3])
            link = pd(item, p[4])
            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,
            })
        result = {
            'list': videos
        }
        return result

H
hjdhnx 已提交
442 443
if __name__ == '__main__':
    from utils import parser
H
hjdhnx 已提交
444
    # js_path = f'js/玩偶姐姐.js'
445
    js_path = f'js/555影视.js'
H
hjdhnx 已提交
446 447 448
    ctx, js_code = parser.runJs(js_path)
    rule = ctx.eval('rule')
    cms = CMS(rule)
H
hjdhnx 已提交
449
    print(cms.title)
H
hjdhnx 已提交
450
    print(cms.homeContent())
451
    # print(cms.categoryContent('20',1))
452
    # print(cms.categoryContent('latest',1))
H
hjdhnx 已提交
453
    # print(cms.detailContent(['https://hongkongdollvideo.com/video/b22c7cb6df40a3c4.html']))
H
hjdhnx 已提交
454
    # cms.categoryContent('dianying',1)
H
hjdhnx 已提交
455
    # print(cms.detailContent(['67391']))
456
    # print(cms.searchContent('斗罗大陆'))