parser.py 6.6 KB
Newer Older
H
hjdhnx 已提交
1 2 3 4 5 6 7
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# File  : parser.py
# Author: DaShenHan&道长-----先苦后甜,任凭晚风拂柳颜------
# Date  : 2022/8/25

import os
H
hjdhnx 已提交
8
import shutil
H
hjdhnx 已提交
9 10

import requests
H
hjdhnx 已提交
11
from flask import make_response, jsonify
H
hjdhnx 已提交
12 13 14 15
from functools import partial  # 这玩意儿能锁定一个函数的参数
import subprocess
subprocess.Popen = partial(subprocess.Popen, encoding="utf-8")  # 固定写法
# 解决execjs执行js时产生的乱码报错,需要在导入该模块之前,让Popen的encoding参数锁定为utf-8
H
hjdhnx 已提交
16 17
# import execjs
import js2py
H
hjdhnx 已提交
18
from js2py.base import JsObjectWrapper,PyJsString,PyJsObject
H
hjdhnx 已提交
19 20 21 22

# os.environ["EXECJS_RUNTIME"] = "JScript"
# print(execjs.get().name)

H
hjdhnx 已提交
23 24 25 26 27 28 29 30
def runJScode(jscode,loader=None,ctx=None):
    if loader is None:
        if ctx is None:
            ctx = {}
        loader = js2py.EvalJs(ctx)
    loader.execute(jscode)
    return loader, jscode

H
hjdhnx 已提交
31
def runJs(jsPath, before='', after='', ctx=None):
H
hjdhnx 已提交
32 33 34
    # base_path = os.path.dirname(os.path.abspath(__file__)) # 当前文件所在目录
    # base_path = os.path.dirname(os.getcwd()) # 当前主程序所在工作目录
    # base_path = os.path.dirname(os.path.abspath('.')) # 上级目录
H
hjdhnx 已提交
35
    # js_code = 'var rule={}'
H
hjdhnx 已提交
36 37
    if ctx is None:
        ctx = {}
H
hjdhnx 已提交
38
    base_path = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))  # 上级目录
H
hjdhnx 已提交
39
    if str(jsPath).startswith('http'):
H
hjdhnx 已提交
40 41 42 43
        js_name = jsPath.split('/')[-1]
        cache_path = os.path.join(base_path, f'cache/{js_name}')
        if not os.path.exists(cache_path):
            try:
H
hjdhnx 已提交
44
                print(f'开始缓存远程规则:{js_name},来源{jsPath}')
H
hjdhnx 已提交
45 46
                js_code = requests.get(url=jsPath,timeout=3).text
                # js_code = requests.get(jsPath).text
H
hjdhnx 已提交
47 48 49 50 51 52 53 54
                with open(cache_path,mode='w+',encoding='utf-8') as f:
                    f.write(js_code)
            except Exception as e:
                print('发生了错误:',e)
                return None, ''
        else:
            with open(cache_path, 'r', encoding='UTF-8') as fp:
                js_code = fp.read()
H
hjdhnx 已提交
55 56
    else:
        js_path = os.path.join(base_path, jsPath)
H
hjdhnx 已提交
57 58 59 60
        if not os.path.exists(js_path):
            return None,''
        js_name = jsPath.split('/')[-1]
        cache_path = os.path.join(base_path, f'cache/{js_name}')
H
md  
hjdhnx 已提交
61 62
        if not str(jsPath).startswith('js/') and not os.path.exists(cache_path) and os.path.exists(js_path):
            shutil.copy(js_path,cache_path) # 本地txt目录的复制过去凑数,实际不使用
H
hjdhnx 已提交
63
        # print(js_path)
H
hjdhnx 已提交
64 65
        with open(js_path, 'r', encoding='UTF-8') as fp:
            js_code = fp.read()
H
hjdhnx 已提交
66
    # print(js_code)
67
    jscode_to_run = js_code
68
    # print(jscode_to_run)
69 70 71 72
    if before:
        jscode_to_run = before + jscode_to_run
    if after:
        jscode_to_run += after
H
hjdhnx 已提交
73
    loader = js2py.EvalJs(ctx)
H
hjdhnx 已提交
74
    return runJScode(jscode_to_run,loader)
H
hjdhnx 已提交
75
    # loader = execjs.compile(jscode_to_run)
H
hjdhnx 已提交
76 77 78
    # print(jscode_to_run)
    # loader.execute(jscode_to_run)
    # return loader,js_code
H
hjdhnx 已提交
79

H
hjdhnx 已提交
80
def toJs(jsPath,jsRoot='cache'):
H
hjdhnx 已提交
81
    base_path = os.path.dirname(os.path.abspath(os.path.dirname(__file__))) # 上级目录
H
hjdhnx 已提交
82
    js_path = os.path.join(base_path, f'{jsRoot}/{jsPath}')
H
hjdhnx 已提交
83
    print(js_path)
H
hjdhnx 已提交
84 85 86 87 88 89 90 91 92 93
    if not os.path.exists(js_path):
        return jsonify({'code': -2, 'msg': f'非法猥亵,文件不存在'})
    with open(js_path, 'r', encoding='UTF-8') as fp:
        js = fp.read()
    response = make_response(js)
    response.headers['Content-Type'] = 'text/javascript; charset=utf-8'
    return response

def toHtml(jsPath):
    base_path = os.path.dirname(os.path.abspath(os.path.dirname(__file__))) # 上级目录
H
hjdhnx 已提交
94
    js_path = os.path.join(base_path, f'cache/{jsPath}')
H
hjdhnx 已提交
95 96 97 98 99
    with open(js_path, 'r', encoding='UTF-8') as fp:
        js = fp.read()
    response = make_response(js)
    response.headers['Content-Type'] = 'text/html; charset=utf-8'
    return response
H
hjdhnx 已提交
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119

def runPy(pyPath):
    # base_path = os.path.dirname(os.path.abspath(__file__)) # 当前文件所在目录
    # base_path = os.path.dirname(os.getcwd()) # 当前主程序所在工作目录
    # base_path = os.path.dirname(os.path.abspath('.')) # 上级目录
    # js_code = 'var rule={}'
    if pyPath and not str(pyPath).endswith('.py'):
        pyPath += '.py'
    base_path = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))  # 上级目录
    if str(pyPath).startswith('http'):
        py_name = pyPath.split('/')[-1]
        cache_path = os.path.join(base_path, f'cache/{py_name}')
        print('远程免嗅:',py_name)
        if not os.path.exists(cache_path):
            try:
                py_code = requests.get(pyPath,timeout=2).text
                with open(cache_path,mode='w+',encoding='utf-8') as f:
                    f.write(py_code)
            except Exception as e:
                print('发生了错误:',e)
H
hjdhnx 已提交
120
                return None
H
hjdhnx 已提交
121 122 123 124 125 126 127 128 129 130 131 132
        else:
            with open(cache_path, 'r', encoding='UTF-8') as fp:
                py_code = fp.read()
    else:
        py_root = os.path.join(base_path, 'py/')
        os.makedirs(py_root,exist_ok=True)
        py_path = os.path.join(py_root, pyPath)
        if not os.path.exists(py_path):
            return ''
        with open(py_path, 'r', encoding='UTF-8') as fp:
            py_code = fp.read()
    # print(js_code)
H
hjdhnx 已提交
133 134 135 136 137 138 139 140 141 142
    return py_code

def covert_demo():
    ctx = {'py_sum':sum,'requests':requests}
    loader = js2py.EvalJs(ctx)
    # loader.execute('var a=py_sum(2,3);function f(x) {return x*x} var b=[a,"5"];var c={"a":a};')
    # loader.execute('var a=py_sum(2,3);function f(x) {return x*x}')
    loader.execute('function f(x) {return x*x};var a=py_sum([2,3]);var b=[a,5];var c={"a":a};')
    f = loader.f
    print(f(8))
H
hjdhnx 已提交
143
    print(f.toString())
H
hjdhnx 已提交
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
    print(loader.eval('py_sum(new Array(1, 2, 3))'))
    print(loader.eval('py_sum([1, 2])'))
    a = loader.a
    print(type(a),a)
    b = loader.b
    b.push(6)
    print(type(b),b)
    b = b.to_list()
    print(type(b),b)
    c = loader.c
    print(type(c),c)
    c = c.to_dict()
    print(type(c), c)
    # CryptoJS = js2py.require('crypto-js')
    # print(type(CryptoJS))
    # print(js2py.require('underscore'))
    JSON = js2py.eval_js('JSON')
    r = JSON.parse('[{"a":1}]')
    print(type(r),r)
    print(r[0].a)
    print(loader.eval('r = requests.get("https://www.baidu.com/");r.encoding = "utf-8";r.text'))
    # 下面是错误用法,没有loader环境没法正确eval_js,有loader用eval不需要eval_js
H
hjdhnx 已提交
166
    # print(js2py.eval_js('r = requests.get("https://www.baidu.com/");r.encoding = "utf-8";r.text'))
167
    with open('../js/蓝莓影视.js',encoding='utf-8') as f:
H
hjdhnx 已提交
168 169
        yk = f.read()
    print(yk)
H
hjdhnx 已提交
170 171 172 173


if __name__ == '__main__':
    covert_demo()