parser.py 6.0 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 9

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

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

H
hjdhnx 已提交
21 22 23 24 25 26 27 28
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 已提交
29
def runJs(jsPath, before='', after='', ctx=None):
H
hjdhnx 已提交
30 31 32
    # 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 已提交
33
    # js_code = 'var rule={}'
H
hjdhnx 已提交
34 35
    if ctx is None:
        ctx = {}
H
hjdhnx 已提交
36
    base_path = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))  # 上级目录
H
hjdhnx 已提交
37
    if str(jsPath).startswith('http'):
H
hjdhnx 已提交
38 39 40 41 42 43 44 45 46 47 48 49 50 51
        js_name = jsPath.split('/')[-1]
        cache_path = os.path.join(base_path, f'cache/{js_name}')
        print('远程规则:',js_name)
        if not os.path.exists(cache_path):
            try:
                js_code = requests.get(jsPath,timeout=2).text
                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 已提交
52 53 54 55
    else:
        js_path = os.path.join(base_path, jsPath)
        with open(js_path, 'r', encoding='UTF-8') as fp:
            js_code = fp.read()
H
hjdhnx 已提交
56
    # print(js_code)
57 58 59 60 61
    jscode_to_run = js_code
    if before:
        jscode_to_run = before + jscode_to_run
    if after:
        jscode_to_run += after
H
hjdhnx 已提交
62
    loader = js2py.EvalJs(ctx)
H
hjdhnx 已提交
63
    return runJScode(jscode_to_run,loader)
H
hjdhnx 已提交
64
    # loader = execjs.compile(jscode_to_run)
H
hjdhnx 已提交
65 66 67
    # print(jscode_to_run)
    # loader.execute(jscode_to_run)
    # return loader,js_code
H
hjdhnx 已提交
68 69 70

def toJs(jsPath):
    base_path = os.path.dirname(os.path.abspath(os.path.dirname(__file__))) # 上级目录
H
hjdhnx 已提交
71 72
    js_path = os.path.join(base_path, f'cache/{jsPath}')
    print(js_path)
H
hjdhnx 已提交
73 74 75 76 77 78 79 80 81 82
    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 已提交
83
    js_path = os.path.join(base_path, f'cache/{jsPath}')
H
hjdhnx 已提交
84 85 86 87 88
    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 已提交
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108

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 已提交
109
                return None
H
hjdhnx 已提交
110 111 112 113 114 115 116 117 118 119 120 121
        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 已提交
122 123 124 125 126 127 128 129 130 131
    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 已提交
132
    print(f.toString())
H
hjdhnx 已提交
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
    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 已提交
155 156 157 158
    # print(js2py.eval_js('r = requests.get("https://www.baidu.com/");r.encoding = "utf-8";r.text'))
    with open('../js/夜空.js',encoding='utf-8') as f:
        yk = f.read()
    print(yk)
H
hjdhnx 已提交
159 160 161 162


if __name__ == '__main__':
    covert_demo()