rules.py 10.6 KB
Newer Older
H
hjdhnx 已提交
1 2 3 4 5
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# File  : rules.py.py
# Author: DaShenHan&道长-----先苦后甜,任凭晚风拂柳颜------
# Date  : 2022/8/25
H
hjdhnx 已提交
6
import json
H
hjdhnx 已提交
7
import os
H
hjdhnx 已提交
8 9
from time import time
import js2py
H
hjdhnx 已提交
10
from quickjs import Function,Context
H
hjdhnx 已提交
11
from utils.log import logger
H
hjdhnx 已提交
12 13
# from utils.web import get_interval,UA
from utils.ua import UA,get_interval
H
hjdhnx 已提交
14
from flask import render_template_string
H
hjdhnx 已提交
15
import ujson
H
hjdhnx 已提交
16

17
def getRuleLists():
H
hjdhnx 已提交
18 19 20
    base_path = os.path.dirname(os.path.abspath(__file__)) # 当前文件所在目录
    # print(base_path)
    file_name = os.listdir(base_path)
21
    file_name = list(filter(lambda x:str(x).endswith('.js') and str(x).find('模板') < 0,file_name))
H
hjdhnx 已提交
22 23 24 25 26
    # print(file_name)
    rule_list = [file.replace('.js','') for file in file_name]
    # print(rule_list)
    return rule_list

H
hjdhnx 已提交
27 28 29 30 31 32 33
def getCacheCount():
    base_path = 'cache/'  # 当前缓存js所在目录
    os.makedirs(base_path, exist_ok=True)
    file_name = os.listdir(base_path)
    file_name = list(filter(lambda x: str(x).endswith('.js') and str(x).find('模板') < 0, file_name))
    return len(file_name)

H
hjdhnx 已提交
34
def getRulesJs2py(path='cache',js_mode=0):
H
hjdhnx 已提交
35
    t1 = time()
H
hjdhnx 已提交
36

H
hjdhnx 已提交
37 38 39 40 41 42 43 44 45
    base_path = path+'/'  # 当前文件所在目录
    # print(base_path)
    os.makedirs(base_path,exist_ok=True)
    file_name = os.listdir(base_path)
    file_name = list(filter(lambda x: str(x).endswith('.js') and str(x).find('模板') < 0, file_name))
    # print(file_name)
    rule_list = [file.replace('.js', '') for file in file_name]
    js_path = [f'{path}/{rule}.js' for rule in rule_list]
    with open('js/模板.js', encoding='utf-8') as f:
H
hjdhnx 已提交
46 47
        # before = f.read().split('export')[0]
        before = f.read().split('export default')[0]
H
hjdhnx 已提交
48 49 50 51 52 53 54 55 56 57 58 59
    rule_codes = []
    # for js in js_path:
    #     with open(js,encoding='utf-8') as f:
    #         code = f.read()
    #         rule_codes.append(js2py.eval_js(before+code))

    ctx = js2py.EvalJs()
    codes = []
    for i in range(len(js_path)):
        js = js_path[i]
        with open(js,encoding='utf-8') as f:
            code = f.read()
H
hjdhnx 已提交
60 61 62
            new_code = 'var muban = JSON.parse(JSON.stringify(mubanDict));\n'+code.replace('rule',f'rule{i}',1)
            # new_code = ''+code.replace('rule',f'rule{i}',1)
            codes.append(new_code)
H
hjdhnx 已提交
63 64
    newCodes = before + '\n'+ '\n'.join(codes)
    # print(newCodes)
H
hjdhnx 已提交
65 66 67 68
    try:
        ctx.execute(newCodes)
        for i in range(len(js_path)):
            rule_codes.append(ctx.eval(f'rule{i}'))
H
hjdhnx 已提交
69

H
hjdhnx 已提交
70 71 72 73
        # print(type(rule_codes[0]),rule_codes[0])
        # print(rule_codes[0].title)
        # print(rule_codes[0].searchable)
        # print(rule_codes[0].quickSearch)
H
hjdhnx 已提交
74
        # rule_codes 是个 js2py.base.JsObjectWrapper 类型,所以下面才能用. 获取属性
H
hjdhnx 已提交
75 76
        new_rule_list = []
        for i in range(len(rule_list)):
H
hjdhnx 已提交
77
            # 过滤排除drpy
H
hjdhnx 已提交
78 79
            if js_mode == 1 and rule_list[i] == 'drpy':
                continue
H
hjdhnx 已提交
80
            sable = rule_codes[i].searchable or 0
H
hjdhnx 已提交
81 82
            tmpObj = {
                'name':rule_list[i],
H
hjdhnx 已提交
83 84
                # 'searchable':1 if (js_mode==1 and sable==2) else sable, # 对js模式1开放软件聚搜(还是算了,服务器遭不住)
                'searchable':sable,
H
hjdhnx 已提交
85 86 87 88 89 90 91 92 93 94 95
                'quickSearch':rule_codes[i].quickSearch or 0,
                'filterable':rule_codes[i].filterable or 0,
            }
            if rule_codes[i].multi:
                tmpObj['multi'] = 1
            new_rule_list.append(tmpObj)
        # print(new_rule_list)
        rules = {'list': new_rule_list, 'count': len(rule_list)}
    except Exception as e:
        logger.info(f'装载js内置源列表失败,置空内置源')
        rules = []
H
hjdhnx 已提交
96 97 98
    logger.info(f'自动配置装载耗时:{get_interval(t1)}毫秒')
    return rules

H
hjdhnx 已提交
99 100 101 102 103 104 105 106 107 108
def getRules(path='cache',js_mode=0):
    t1 = time()

    base_path = path+'/'  # 当前文件所在目录
    os.makedirs(base_path,exist_ok=True)
    file_name = os.listdir(base_path)
    file_name = list(filter(lambda x: str(x).endswith('.js') and str(x).find('模板') < 0, file_name))
    rule_list = [file.replace('.js', '') for file in file_name]
    js_path = [f'{path}/{rule}.js' for rule in rule_list]
    with open('js/模板.js', encoding='utf-8') as f:
H
hjdhnx 已提交
109 110
        # before = f.read().split('export')[0]
        before = f.read().split('export default')[0]
H
hjdhnx 已提交
111 112 113 114 115 116 117
    rule_codes = []
    ctx = Context()
    codes = []
    for i in range(len(js_path)):
        js = js_path[i]
        with open(js,encoding='utf-8') as f:
            code = f.read()
H
hjdhnx 已提交
118
            new_code = 'var muban = JSON.parse(JSON.stringify(mubanDict));\n'+code.replace('var rule',f'var rule{i}',1)+f'\nif (rule{i}.模板 && muban.hasOwnProperty(rule{i}.模板))'+'{'+f'rule{i} = Object.assign(muban[rule{i}.模板], rule{i});'+'}'
H
hjdhnx 已提交
119 120 121 122 123 124 125 126 127 128 129 130
            # new_code = ''+code.replace('rule',f'rule{i}',1)
            codes.append(new_code)
    newCodes = before + '\n'+ '\n'.join(codes)
    # print(newCodes)
    try:
        ctx.eval(newCodes)
        for i in range(len(js_path)):
            rule_codes.append(ctx.get(f'rule{i}'))

        # rule_codes 是个 js2py.base.JsObjectWrapper 类型,所以下面才能用. 获取属性
        new_rule_list = []
        for i in range(len(rule_list)):
H
hjdhnx 已提交
131 132 133
            # 过滤排除drpy
            # if js_mode == 1 and rule_list[i] == 'drpy':
            #     continue
H
hjdhnx 已提交
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
            rule_codes[i] = ujson.loads(rule_codes[i].json())
            sable = rule_codes[i].get('searchable',0)
            tmpObj = {
                'name':rule_list[i],
                # 'searchable':1 if (js_mode==1 and sable==2) else sable, # 对js模式1开放软件聚搜(还是算了,服务器遭不住)
                'searchable':sable,
                'quickSearch': rule_codes[i].get('quickSearch',0),
                'filterable': rule_codes[i].get('filterable',0),
            }
            # print(tmpObj)
            if rule_codes[i].get('multi'):
                tmpObj['multi'] = 1
            new_rule_list.append(tmpObj)
        # print(new_rule_list)
        rules = {'list': new_rule_list, 'count': len(rule_list)}
    except Exception as e:
H
hjdhnx 已提交
150 151
        logger.info(f'装载js内置源列表失败,置空内置源:{e}')
        rules = {'list': [], 'count': 0}
H
hjdhnx 已提交
152 153 154
    logger.info(f'自动配置装载耗时:{get_interval(t1)}毫秒')
    return rules

H
hjdhnx 已提交
155 156 157 158 159 160
def jxTxt2Json(text:str,host:str):
    try:
        data = render_template_string(text,host=host).strip().split('\n')
    except Exception as e:
        logger.info(f'jxTxt2Json发生错误:{e}')
        data = []
H
hjdhnx 已提交
161
    jxs = []
162
    for i in data:
H
hjdhnx 已提交
163 164
        i = i.strip()
        dt = i.split(',')
H
hjdhnx 已提交
165 166 167 168 169
        if not i.startswith('#') and len(i) > 10:
            try:
                jxs.append({
                    'name':dt[0],
                    'url':dt[1],
H
hjdhnx 已提交
170 171
                    'type':dt[2] if len(dt) > 2 and dt[2] else 0,
                    'ua':dt[3] if len(dt) > 3 and dt[3] else UA,
H
hjdhnx 已提交
172 173 174
                })
            except Exception as e:
                logger.info(f'解析行有错误:{e}')
175 176
    return jxs

H
hjdhnx 已提交
177
def getJxs(path='js',host=None):
178 179 180 181 182 183 184 185 186 187
    custom_jx = 'base/解析.conf'
    if not os.path.exists(custom_jx):
        with open(custom_jx,'w+',encoding='utf-8') as f1:
            msg = """# 这是用户自定义解析列表,不会被系统升级覆盖
# 0123,对应,普通解析,json解析,并发多json解析,聚合解析,参数3不填默认0
# flags是线路名称标识,会自动拦截并走以下的解析
# 名称,链接,类型,ua (ua不填默认 Mozilla/5.0) 可以手动填 Dart/2.14 (dart:io)
虾米,https://dm.xmflv.com:4433/?url=
            """
            f1.write(msg)
H
hjdhnx 已提交
188 189 190
    base_path = 'jiexi'  # 自建解析目录
    os.makedirs(base_path, exist_ok=True)
    file_name = os.listdir(base_path)
191
    file_name = list(filter(lambda x: str(x).endswith('.js') and str(x).find('模板') < 0 and str(x).find('加密') < 0, file_name))
H
hjdhnx 已提交
192 193 194 195 196 197
    # print(file_name)
    jx_list = [file.replace('.js', '') for file in file_name]
    # print(file_name)
    # print(jx_list)
    jx_str = '\n'.join([jx+',{{host}}'+f'/parse/api/{jx}.js?url=,1' for jx in jx_list])
    # print(jx_str)
198 199 200

    with open(f'{path}/解析.conf',encoding='utf-8') as f:
        text = f.read()
H
hjdhnx 已提交
201
    text = jx_str + '\n' + text
H
hjdhnx 已提交
202
    jxs = jxTxt2Json(text,host)
203 204
    with open(custom_jx,encoding='utf-8') as f2:
        text = f2.read()
H
hjdhnx 已提交
205
    jxs2 = jxTxt2Json(text,host)
206
    jxs.extend(jxs2)
H
hjdhnx 已提交
207 208 209
    print(f'共计{len(jxs)}条解析')
    return jxs

H
hjdhnx 已提交
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
def getPys(path='txt/py'):
    t1 = time()
    base_path = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))  # 上级目录
    py_path = os.path.join(base_path, path)
    os.makedirs(py_path, exist_ok=True)
    file_name = os.listdir(py_path)
    file_name = list(filter(lambda x: str(x).endswith('.py'), file_name))
    # print(file_name)
    rule_list = [file.replace('.py', '') for file in file_name]
    py_path = [f'{path}/{rule}.py' for rule in rule_list]
    new_rule_list = []
    for i in range(len(rule_list)):
        new_rule_list.append({
            'name': rule_list[i],
            'searchable': 1,
            'quickSearch': 1,
            'filterable': 0,
        })
    logger.info(f'自动加载Pyramid耗时:{get_interval(t1)}毫秒')
    return new_rule_list

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 261
def gen_cache(path='txt/js/tg'):
    t1 = time()
    base_path = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))  # 上级目录
    py_path = os.path.join(base_path, path)
    os.makedirs(py_path, exist_ok=True)
    file_name = os.listdir(py_path)
    file_name = list(filter(lambda x: str(x).endswith('.js'), file_name))
    # print(file_name)
    rule_list = [file.replace('.js', '') for file in file_name]
    js_path = [f'{path}/{rule}.js' for rule in rule_list]
    new_rule_list = []
    for i in range(len(rule_list)):
        # print(js_path[i])
        rname = rule_list[i]
        new_rule_list.append(
            {
                "key": f"dr_{rname}",
                "name": f"{rname}(道长)",
                "type": 1,
                # "api": "{{host}}"+f"/vod?rule={rname}&ext="+"{{host}}/"+js_path[i],
                "api": "{{host}}"+f"/vod?rule={rname}&ext="+js_path[i],
                "searchable": 2,
                "quickSearch": 0,
                "filterable": 0
            })
    logger.info(f'自动加载{len(new_rule_list)}个缓存JS耗时:{get_interval(t1)}毫秒')
    new_rules_texts = [json.dumps(new_rule,ensure_ascii=False) for new_rule in new_rule_list]
    # new_rules_text = json.dumps(new_rule_list,ensure_ascii=False)
    new_rules_text = ',\n'.join(new_rules_texts)+','
    return new_rules_text

H
hjdhnx 已提交
262
if __name__ == '__main__':
H
hjdhnx 已提交
263
    print(getRuleLists())
H
hjdhnx 已提交
264 265 266 267 268 269 270
    # print(gen_cache())
    # print(gen_cache('txt/js/18'))

    custom_file = gen_cache() + '\n'+gen_cache('txt/js/18')
    print(custom_file)
    with open('custom.conf','w+',encoding='utf-8') as f:
        f.write(custom_file)