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

import base64
H
hjdhnx 已提交
8 9
import math
import re
H
hjdhnx 已提交
10
from urllib.parse import urljoin,quote,unquote
H
hjdhnx 已提交
11
from js2py.base import PyJsString
H
hjdhnx 已提交
12 13 14 15 16 17
import requests,warnings
# 关闭警告
warnings.filterwarnings("ignore")
from requests.packages import urllib3
urllib3.disable_warnings()

18
import requests.utils
H
hjdhnx 已提交
19
import hashlib
20
from time import sleep
21
import os
H
hjdhnx 已提交
22
from utils.web import UC_UA,PC_UA
H
hjdhnx 已提交
23
from ast import literal_eval
H
hjdhnx 已提交
24
from utils.log import logger
H
hjdhnx 已提交
25
import quickjs
H
hjdhnx 已提交
26

27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
def getPreJs():
    base_path = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))  # 上级目
    lib_path = os.path.join(base_path, f'libs/pre.js')
    with open(lib_path,encoding='utf-8') as f:
        code = f.read()
    return code

def getCryptoJS():
    base_path = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))  # 上级目
    os.makedirs(os.path.join(base_path, f'libs'), exist_ok=True)
    lib_path = os.path.join(base_path, f'libs/crypto-hiker.js')
    # print('加密库地址:', lib_path)
    if not os.path.exists(lib_path):
        return 'undefiend'
    with open(lib_path,encoding='utf-8') as f:
        code = f.read()
    return code

H
hjdhnx 已提交
45 46 47
def md5(str):
    return hashlib.md5(str.encode(encoding='UTF-8')).hexdigest()

H
hjdhnx 已提交
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
def getLib(js):
    base_path = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))  # 上级目录
    lib_path = os.path.join(base_path, f'libs/{js}')
    if not os.path.exists(lib_path):
        return ''
    with open(lib_path,encoding='utf-8') as f:
        return f.read()

# def atob(text):
#     if isinstance(text,PyJsString):
#         text = parseText(str(text))
#     qjs = quickjs.Context()
#     print(text)
#     js = getLib('atob.js')
#     print(js)
#     ret = qjs.eval(f'{js};atob("{text}")')
#     print(ret)

def atob(text):
    """
    解码
    :param text:
    :return:
    """
    if isinstance(text,PyJsString):
        text = parseText(str(text))
    return base64.b64decode(text.encode("utf8")).decode("latin1")

def btoa(text):
    """
    编码
    :param text:
    :return:
    """
    if isinstance(text,PyJsString):
        text = parseText(str(text))
    return base64.b64encode(text.encode("latin1")).decode("utf8")

H
hjdhnx 已提交
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
def requireCache(lib:str):
    base_path = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))  # 上级目
    os.makedirs(os.path.join(base_path, f'libs'), exist_ok=True)
    logger.info(f'开始加载:{lib}')
    code = 'undefiend'
    if not lib.startswith('http'):
        lib_path = os.path.join(base_path, f'libs/{lib}')
        if not os.path.exists(lib_path):
            pass
        else:
            with open(lib_path, encoding='utf-8') as f:
                code = f.read()
    else:
        lib_path = os.path.join(base_path, f'libs/{md5(lib)}.js')
        if not os.path.exists(lib_path):
            try:
                r = requests.get(lib,headers={
                    'Referer': lib,
                    'User-Agent': UC_UA,
H
hjdhnx 已提交
105
                },timeout=5,verify=False)
H
hjdhnx 已提交
106 107 108 109 110 111 112 113 114 115 116 117
                with open(lib_path,mode='wb+') as f:
                    f.write(r.content)
                code =  r.text
            except Exception as e:
                print(f'获取远程依赖失败:{e}')
        else:
            with open(lib_path,encoding='utf-8') as f:
                code = f.read()
    # print(code)
    return code


118 119 120 121 122 123
def getHome(url):
    # http://www.baidu.com:9000/323
    urls = url.split('//')
    homeUrl = urls[0] + '//' + urls[1].split('/')[0]
    return homeUrl

124 125 126 127 128 129
class OcrApi:
    def __init__(self,api):
        self.api = api

    def classification(self,img):
        try:
H
hjdhnx 已提交
130
            code = requests.post(self.api,data=img,headers={'user-agent':PC_UA},verify=False).text
131 132 133 134 135 136 137
        except Exception as e:
            print(f'ocr识别发生错误:{e}')
            code = ''
        return code

def verifyCode(url,headers,timeout=5,total_cnt=3,api=None):
    if not api:
138 139
        # api = 'http://192.168.3.224:9000/api/ocr_img'
        api = 'http://dm.mudery.com:10000'
140 141 142 143 144 145
    lower_keys = list(map(lambda x: x.lower(), headers.keys()))
    host = getHome(url)
    if not 'referer' in lower_keys:
        headers['Referer'] = host
    print(f'开始自动过验证,请求头:{headers}')
    cnt = 0
146
    ocr = OcrApi(api)
147 148 149
    while cnt < total_cnt:
        s = requests.session()
        try:
H
hjdhnx 已提交
150
            img = s.get(url=f"{host}/index.php/verify/index.html", headers=headers,timeout=timeout,verify=False).content
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
            code = ocr.classification(img)
            print(f'第{cnt+1}次验证码识别结果:{code}')
            res = s.post(
                url=f"{host}/index.php/ajax/verify_check?type=search&verify={code}",
                headers=headers).json()
            if res["msg"] == "ok":
                cookies_dict = requests.utils.dict_from_cookiejar(s.cookies)
                cookie_str = ';'.join([f'{k}={cookies_dict[k]}' for k in cookies_dict])
                # return cookies_dict
                return cookie_str
        except:
            print(f'第{cnt+1}次验证码提交失败')
            pass
        cnt += 1
        sleep(1)
    return ''

H
hjdhnx 已提交
168
def base64Encode(text):
H
hjdhnx 已提交
169 170
    if isinstance(text,PyJsString):
        text = str(text).replace("'","").replace('"','')
H
hjdhnx 已提交
171 172
    return base64.b64encode(text.encode("utf8")).decode("utf-8") #base64编码

H
hjdhnx 已提交
173 174 175 176
def base64Decode(text):
    if isinstance(text,PyJsString):
        text = parseText(str(text))
    # print(text)
H
hjdhnx 已提交
177 178
    return base64.b64decode(text).decode("utf-8") #base64解码

H
hjdhnx 已提交
179 180
def parseText(text:str):
    text = text.replace('false','False').replace('true','True').replace('null','None')
H
hjdhnx 已提交
181
    # print(text)
H
hjdhnx 已提交
182 183
    return literal_eval(text)

H
hjdhnx 已提交
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 setDetail(title:str,img:str,desc:str,content:str,tabs:list=None,lists:list=None):
    vod = {
        "vod_name": title.split('/n')[0],
        "vod_pic": img,
        "type_name": title,
        "vod_year": "",
        "vod_area": "",
        "vod_remarks": desc,
        "vod_actor": "",
        "vod_director": "",
        "vod_content": content
    }
    return vod

def urljoin2(a,b):
    a = str(a).replace("'",'').replace('"','')
    b = str(b).replace("'",'').replace('"','')
    # print(type(a),a)
    # print(type(b),b)
    ret = urljoin(a,b)
    return ret

def join(lists,string):
    """
    残废函数,没法使用
    :param lists:
    :param string:
    :return:
    """
    # FIXME
    lists1 = lists.to_list()
    string1 = str(string)
    print(type(lists1),lists1)
    print(type(string1),string1)
    try:
        ret = string1.join(lists1)
        print(ret)
        return ret
    except Exception as e:
        print(e)
        return ''

H
hjdhnx 已提交
226 227 228
def dealObj(obj=None):
    if not obj:
        obj = {}
H
hjdhnx 已提交
229 230
    encoding = obj.get('encoding') or 'utf-8'
    encoding = str(encoding).replace("'", "")
H
hjdhnx 已提交
231
    # encoding = parseText(str(encoding))
H
hjdhnx 已提交
232 233
    method = obj.get('method') or 'get'
    method = str(method).replace("'", "")
H
hjdhnx 已提交
234
    # method = parseText(str(method))
H
优化  
hjdhnx 已提交
235 236
    withHeaders = obj.get('withHeaders') or ''
    withHeaders = str(withHeaders).replace("'", "")
H
hjdhnx 已提交
237
    # withHeaders = parseText(str(withHeaders))
H
hjdhnx 已提交
238 239 240 241 242 243 244 245 246 247 248 249 250
    # print(type(url),url)
    # headers = dict(obj.get('headers')) if obj.get('headers') else {}
    # headers = obj.get('headers').to_dict() if obj.get('headers') else {}
    headers = obj.get('headers') if obj.get('headers') else {}
    new_headers = {}
    # print(type(headers),headers)
    for i in headers:
        new_headers[str(i).replace("'", "")] = str(headers[i]).replace("'", "")
    # print(type(new_headers), new_headers)

    timeout = float(obj.get('timeout').to_int()) if obj.get('timeout') else None
    # print(type(timeout), timeout)
    body = obj.get('body') if obj.get('body') else {}
H
hjdhnx 已提交
251 252 253 254 255 256 257 258 259 260
    # print(body)
    # print(type(body))
    if isinstance(body,PyJsString):
        body = parseText(str(body))
        new_dict = {}
        new_tmp = body.split('&')
        for i in new_tmp:
            new_dict[i.split('=')[0]] = i.split('=')[1]
        body = new_dict

H
hjdhnx 已提交
261 262 263
    new_body = {}
    for i in body:
        new_body[str(i).replace("'", "")] = str(body[i]).replace("'", "")
H
hjdhnx 已提交
264 265 266 267 268
    return {
        'encoding':encoding,
        'headers':new_headers,
        'timeout':timeout,
        'body': new_body,
H
优化  
hjdhnx 已提交
269 270
        'method':method,
        'withHeaders':withHeaders
H
hjdhnx 已提交
271 272
    }

H
hjdhnx 已提交
273 274 275 276 277 278
def coverDict2form(data:dict):
    forms = []
    for k,v in data.items():
        forms.append(f'{k}={v}')
    return '&'.join(forms)

H
hjdhnx 已提交
279
def base_request(url,obj):
H
hjdhnx 已提交
280
    # verify=False 关闭证书验证
H
hjdhnx 已提交
281
    # print(obj)
H
hjdhnx 已提交
282
    url = str(url).replace("'", "")
H
hjdhnx 已提交
283
    method = obj.get('method') or ''
H
优化  
hjdhnx 已提交
284
    withHeaders = obj.get('withHeaders') or ''
H
hjdhnx 已提交
285
    # print(f'withHeaders:{withHeaders}')
H
hjdhnx 已提交
286 287
    if not method:
        method = 'get'
H
hjdhnx 已提交
288
        obj['method'] = 'method'
H
hjdhnx 已提交
289
    # print(obj)
H
hjdhnx 已提交
290
    print(f"{method}:{url}:{obj['headers']}:{obj.get('body','')}")
H
hjdhnx 已提交
291 292 293
    try:
        # r = requests.get(url, headers=headers, params=body, timeout=timeout)
        if method.lower() == 'get':
H
hjdhnx 已提交
294
            r = requests.get(url, headers=obj['headers'], params=obj['body'], timeout=obj['timeout'],verify=False)
H
hjdhnx 已提交
295
        else:
H
hjdhnx 已提交
296 297 298 299
            # if isinstance(obj['body'],dict):
            #     obj['body'] = coverDict2form(obj['body'])
            # print(obj['body'])
            # 亲测不需要转换data 格式的dict 为 form都正常 (gaze规则和奇优搜索)
H
hjdhnx 已提交
300
            r = requests.post(url, headers=obj['headers'], data=obj['body'], timeout=obj['timeout'],verify=False)
H
hjdhnx 已提交
301 302 303
        # r = requests.get(url, timeout=timeout)
        # r = requests.get(url)
        # print(encoding)
H
hjdhnx 已提交
304
        r.encoding = obj['encoding']
H
hjdhnx 已提交
305
        # print(f'源码:{r.text}')
H
优化  
hjdhnx 已提交
306 307 308 309 310 311 312 313 314
        if withHeaders:
            backObj = {
                'url':r.url,
                'body':r.text,
                'headers':r.headers
            }
            return backObj
        else:
            return r.text
H
hjdhnx 已提交
315 316
    except Exception as e:
        print(f'{method}请求发生错误:{e}')
H
优化  
hjdhnx 已提交
317
        return {} if withHeaders else ''
H
hjdhnx 已提交
318

H
hjdhnx 已提交
319
def fetch(url,obj):
H
hjdhnx 已提交
320
    # print('fetch')
H
hjdhnx 已提交
321
    obj = dealObj(obj)
H
hjdhnx 已提交
322
    if not obj.get('headers') or not any([obj['headers'].get('User-Agent'),obj['headers'].get('user-agent')]):
H
hjdhnx 已提交
323
        obj['headers']['User-Agent'] = obj['headers'].get('user-agent',PC_UA)
H
hjdhnx 已提交
324
    return base_request(url,obj)
H
hjdhnx 已提交
325 326

def post(url,obj):
H
hjdhnx 已提交
327
    obj = dealObj(obj)
H
hjdhnx 已提交
328 329
    obj['method'] = 'post'
    return base_request(url,obj)
H
hjdhnx 已提交
330

H
hjdhnx 已提交
331
def request(url,obj):
H
hjdhnx 已提交
332
    obj = dealObj(obj)
H
hjdhnx 已提交
333
    # print(f'{method}:{url}')
H
hjdhnx 已提交
334
    if not obj.get('headers') or not any([obj['headers'].get('User-Agent'),obj['headers'].get('user-agent')]):
H
hjdhnx 已提交
335
        obj['headers']['User-Agent'] = obj['headers'].get('user-agent',UC_UA)
H
hjdhnx 已提交
336

H
hjdhnx 已提交
337
    return base_request(url, obj)
H
hjdhnx 已提交
338

H
hjdhnx 已提交
339 340 341 342 343 344 345 346 347 348 349 350
def redx(text):
    """
    修正js2py交互的字符串自动加前后引号问题
    :param text:
    :return:
    """
    # return text.replace("'", "").replace('"', "")
    text = str(text)
    if text.startswith("'") and text.endswith("'"):
        text = text[1:-1]
    return text

H
hjdhnx 已提交
351
def buildUrl(url,obj=None):
H
hjdhnx 已提交
352 353
    # url = str(url).replace("'", "")
    url = redx(url)
H
hjdhnx 已提交
354 355 356 357
    if not obj:
        obj = {}
    new_obj = {}
    for i in obj:
H
hjdhnx 已提交
358 359 360
        # new_obj[str(i).replace("'", "")] = str(obj[i]).replace("'", "")
        new_obj[redx(i)] = redx(obj[i])

H
hjdhnx 已提交
361
    if str(url).find('?') < 0:
H
hjdhnx 已提交
362
        url = str(url) + '?'
H
hjdhnx 已提交
363 364 365
    param_list = [f'{i}={new_obj[i]}' for i in new_obj]
    # print(param_list)
    prs = '&'.join(param_list)
H
hjdhnx 已提交
366
    if len(new_obj) > 0 and not str(url).endswith('?'):
H
hjdhnx 已提交
367
        url += '&'
H
hjdhnx 已提交
368 369
    # url = (url + prs).replace('"','').replace("'",'')
    url = url + prs
H
hjdhnx 已提交
370
    # print(url)
H
hjdhnx 已提交
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
    return url

def forceOrder(lists:list,key:str=None,option=None):
    """
    强制正序
    :param lists:
    :param key:
    :return:
    """
    start = math.floor(len(lists)/2)
    end = min(len(lists)-1,start+1)
    if start >= end:
        return lists
    first = lists[start]
    second = lists[end]
    if key:
        try:
            first = first[key]
            second = second[key]
        except:
            pass
    if option and hasattr(option, '__call__'):
        try:
            first = option(first)
            second = option(second)
            # print(f'first:{first},second:{second}')
        except Exception as e:
            print(f'强制排序执行option发生了错误:{e}')
    first = str(first)
    second = str(second)
    if re.search(r'(\d+)',first) and re.search(r'(\d+)',second):
        num1 = int(re.search(r'(\d+)',first).groups()[0])
        num2 = int(re.search(r'(\d+)',second).groups()[0])
        if num1 > num2:
            lists.reverse()

H
hjdhnx 已提交
407 408 409 410 411 412 413 414 415
    return lists

def base64ToImage(image_base64:str):
    if isinstance(image_base64,PyJsString):
        image_base64 = parseText(str(image_base64))
    if ',' in image_base64:
        image_base64 = image_base64.split(',')[1]
    img_data = base64.b64decode(image_base64)
    return img_data