import base64
import ctypes
import hashlib
import hmac
import json
import random
import time
import traceback
from urllib.parse import urlencode, quote

import execjs
import requests
import tls_client
from loguru import logger

from env_captcha import PxEnv
from src.utils import PxUtils

ctx = execjs.compile('''const Ev = (t, e, n) => {
    var r = ie(encode(n), 10), o = [], a = -1;
    for (var i = 0; i < t.length; i++) {
        var l = Math.floor(i / r.length + 1)
        var c = i >= r.length ? i % r.length : i
        var u = r.charCodeAt(c) * r.charCodeAt(l)
        // console.log(i, l, c, u)
        u > a && (a = u)
    }
    for (var f = 0; t.length > f; f++) {
        var s = Math.floor(f / r.length) + 1,
            d = f % r.length,
            p = r.charCodeAt(d) * r.charCodeAt(s)
        // console.log(f, s, d, p, p > e, wv(p, 0, a, 0, e-1))
            p >= e && (p = wv(p, 0, a, 0, e - 1));
            for (; -1 !== o.indexOf(p);) {

                p += 1
            }
        // console.log('add', p)
        o.push(p)
    }

    return o.sort(function (t, e) {
        return t - e
    })
}

const encode = (t) => {
    return btoa(encodeURIComponent(t).replaceAll(/%([0-9A-F]{2})/g, function (t, e) {
        // console.log(t, e, '0x' + e)
        return String.fromCharCode("0x" + e);
    }))
}

const ie = (t, e) => {
    for (var n = '', r = 0; r < t.length; r++)
        // console.log(e, t.charCodeAt(r), e ^ t.charCodeAt(r), String.fromCharCode(e ^ t.charCodeAt(r)))
        n += String.fromCharCode(e ^ t.charCodeAt(r))

    return n
}

const wv = (t, e, n, r, o) => {
    return Math.floor(((t - e) / (n - e)) * (o - r) + r)
}

const Fa = (t, e, n) => {
    // console.log('t', t)
    // console.log('e', e)
    // console.log('n', n)
    var r = '', o = 0, a = t.split('')
    for (var i = 0; i < t.length; i++) {
        // console.log(i,o,n[i], n[i] - i - 1, e.substring(o, n[i] - i - 1), a[i], e.substring(o, n[i] - i - 1)+a[i])
        // console.log(i, o, n[i] - i - 1, n[i] - i - 1 - o)
        r += e.substring(o, n[i] - i - 1)
            + a[i]
        // console.log(e.substring(o, n[i] - i - 1))
        // console.log(r.length, r)
        o = n[i] - i - 1
        // console.log('iii',i,r)
        // console.log()
    }

    console.log(e.substring(o))
    return (r += e.substring(o))
}

function encodePayload(payload, uuid, sts) {
    var sts = sts.length === 0 ? '1604064986000' : sts
    let t1 = ie(payload, 50);
    const BasePayload = encode(t1)
    console.log(BasePayload)
    const fv = ie(encode(sts), 10)
    let t3 = Ev(fv, BasePayload.length, uuid);
    console.log(t3+''
    )
    return Fa(fv, BasePayload, t3)
}''')
ctxPC = execjs.compile(open('pc.js').read())
ctxStep2 = execjs.compile('''
const crypto = require('crypto');
function genUuid(t, e, n, r) {
    function l(t) {
        return l = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (t) {
            return typeof t;
        } : function (t) {
            return t && "function" == typeof Symbol && t.constructor === Symbol && t !== Symbol.prototype ? "symbol" : typeof t;
        }, l(t);
    }

    var nr;
    try {
        if (("undefined" == typeof crypto ? "undefined" : l(crypto)) !== "undefined" && crypto && crypto.getRandomValues) {
            var ar = new Uint8Array(16);
            (nr = function () {
                return crypto.getRandomValues(ar), ar;
            })();
        }
    } catch (t) {
        nr = void 0;
    }

    function xt() {
        return +new Date();
    }

    var sr = nr();
    var hr = [1 | sr[0], sr[1], sr[2], sr[3], sr[4], sr[5]];
    var vr = 16383 & (sr[6] << 8 | sr[7]);
    var dr = 0;
    var pr = 0;
    // uuid
    // return '6172b081-7040-1031-9ca8-44e6194ad09a'
    var a = "";
    if (r) try {
        for (var o = (new Date().getTime() * Math.random() + "").replace(".", ".".charCodeAt()).split("").slice(-16), i = 0; i < o.length; i++) o[i] = parseInt(10 * Math.random()) * +o[i] || parseInt(Math.random() * 36);
        a = $C_gLP(o, 0);
    } catch (t) {
    }
    var c = e && n || 0;
    var u = e || [];
    var l = void 0 !== (t = t || {}).clockseq ? t.clockseq : vr;
    var f = void 0 !== t.msecs ? t.msecs : xt();
    var s = void 0 !== t.nsecs ? t.nsecs : pr + 1;
    var h = f - dr + (s - pr) / 1e4;
    if (h < 0 && void 0 === t.clockseq && (l = l + 1 & 16383), (h < 0 || f > dr) && void 0 === t.nsecs && (s = 0), s >= 1e4) throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");
    dr = f, pr = s, vr = l;
    var v = (1e4 * (268435455 & (f += 122192928e5)) + s) % 4294967296;
    u[c++] = v >>> 24 & 255, u[c++] = v >>> 16 & 255, u[c++] = v >>> 8 & 255, u[c++] = 255 & v;
    var d = f / 4294967296 * 1e4 & 268435455;
    u[c++] = d >>> 8 & 255, u[c++] = 255 & d, u[c++] = d >>> 24 & 15 | 16, u[c++] = d >>> 16 & 255, u[c++] = l >>> 8 | 128, u[c++] = 255 & l;
    for (var p = t.node || hr, m = 0; m < 6; m++) u[c + m] = p[m];
    for (var ir = [], cr = {}, ur = 0; ur < 256; ur++) ir[ur] = (ur + 256).toString(16).substr(1), cr[ir[ur]] = ur;

    function $C_gLP(t, e) {
        var n = e || 0;
        return ir[t[n++]] + ir[t[n++]] + ir[t[n++]] + ir[t[n++]] + "-" + ir[t[n++]] + ir[t[n++]] + "-" + ir[t[n++]] + ir[t[n++]] + "-" + ir[t[n++]] + ir[t[n++]] + "-" + ir[t[n++]] + ir[t[n++]] + ir[t[n++]] + ir[t[n++]] + ir[t[n++]] + ir[t[n++]];
    }

    var g = e || $C_gLP(u);
    return a === g ? a : g;
}''')


def get_timestamp():
    return int(time.time() * 1000)


def unsinged_right_shift(x, y):
    x, y = ctypes.c_uint32(x).value, y % 32
    return ctypes.c_uint32(x >> y).value


class PxBypass():
    # PX11431 o111ooo1
    ts: str = ''
    cs: str = ''
    # PX15454 o111oooo
    num1: int = ''
    # PX11701 111o1o
    num2: str = ''
    # PX11701 111o1o
    str1: str = ''
    vid: str = ''
    sid: str = ''
    cts: str = ''

    tag = "v8.7.2"
    ft = "317"
    appId = "PXVb73hTEg"

    def __init__(self, target_url):
        self.cookies = {}
        self.log = logger.bind(module_name='px')

        envs = json.loads(open('env.json', 'r', encoding='utf-8').read())
        selectId = random.choice(list(envs.keys()))
        self.log.info(f'selectId: {selectId}')
        self.pxEnv = envs[selectId]
        self.ua = self.pxEnv['navigatorparams']['useragent']
        self.ua = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36'
        self.pxHeaders = {
            "authority": "collector-pxvb73hteg.px-cloud.net",
            "accept": "*/*",
            "accept-language": "en-US,en;q=0.9",
            "cache-control": "no-cache",
            "content-type": "application/x-www-form-urlencoded",
            "origin": "https://www.flyfrontier.com",
            "pragma": "no-cache",
            "user-agent": self.ua
        }
        self.pxUrl = f"https://collector-{self.appId}.px-cloud.net/api/v2/collector"
        self.target_url = target_url
        self.session = tls_client.Session(client_identifier='chrome_117')
        # print(session.get('https://tls.peet.ws/api/all').json())
        # session = requests.Session()
        self.session.proxies = {
            'http': 'http://127.0.0.1:7890',
            'https': 'http://127.0.0.1:7890',
        }

        self.session.proxies = {
            'http': "http://unfflcc:76cc14-47b8dd-1f8ace-827836-0c740e@usa.rotating.proxyrack.net:9000",
            'https': "http://unfflcc:76cc14-47b8dd-1f8ace-827836-0c740e@usa.rotating.proxyrack.net:9000",
        }
        # session.proxies = {
        #     'http': 'http://user-uni001-region-us-sessid-1111-sesstime-5-keep-true:q39CEBTs5A5YQXor@pr.roxlabs.cn:4600',
        #     'https': 'http://user-uni001-region-us-sessid-1111-sesstime-5-keep-true:q39CEBTs5A5YQXor@pr.roxlabs.cn:4600',
        # }
        prox = 'http://b6b6b6b6-zone-custom-region-us-session-130oj36t4-sessTime-5:bpoMDFG5oD@na.ipidea.io:2333'

        prox = f'http://user-uni001-region-us-sessid-{random.randint(1000, 5000)}-sesstime-5-keep-true:q39CEBTs5A5YQXor@pr.roxlabs.cn:4600'
        # prox = 'http://unfflcc:76cc14-47b8dd-1f8ace-827836-0c740e@usa.rotating.proxyrack.net:9000'
        # prox = f'http://unfflcc:76cc14-47b8dd-1f8ace-827836-0c740e@usa.rotating.proxyrack.net:{random.randint(10000, 13500)}'
        prox = 'http://127.0.0.1:7890'
        self.session.proxies = {
            'http': prox,
            'https': prox,
        }
        self.prox = prox
        self.log.info(f'proxy: {self.prox}')

        # self.tlsUrl = 'http://52.52.23.116/tls/forward'
        self.tlsUrl = 'http://127.0.0.1:58000/tls/forward'

    def inc(self):
        self.seq += 1
        self.rsc += 1
        self.log.info(f'seq: {self.seq} rsc:{self.rsc}')

    def do_collector(self, data):
        if isinstance(data, list):
            data_str = json.dumps(data, separators=(',', ':'), ensure_ascii=True)
        else:
            data_str = data
        self.log.info(f'data_str {data_str}')
        # self.log.info(f"gen Payload {self.uuid}, {self.ts}")
        # payload = ctx.call('encodePayload', data_str, self.uuid, self.ts)
        payload = PxUtils().encode_payload(payload=data_str, uuid=self.uuid, ts=self.ts)
        # self.log.info(f'payload {payload}')
        pc = self._gen_pc(data_str, f'{self.uuid}:{self.tag}:{self.ft}')
        body = {
            "appId": self.appId,
            "tag": self.tag,
            "uuid": self.uuid,
            "ft": self.ft,
            "seq": self.seq,
            "en": "NTA",
            "pc": pc,
            "rsc": self.rsc,
            "payload": payload,
        }
        body = self.update_sid_vid(body)
        self.log.info(f'postBody {json.dumps(body)}')
        # response = self.session.post(self.pxUrl, headers=self.pxHeaders, data=body)

        response = requests.post(self.tlsUrl,
                                 # response = requests.post('http://127.0.0.1:58000/tls/forward',
                                 json=dict(url=self.pxUrl, headers=self.pxHeaders, method="POST", proxy=self.prox,
                                           debug=True,
                                           data=urlencode(body, doseq=True)
                                           # ,allow_redirects=True

                                           ))
        # self.log.info(f'collector1 {response.text}')
        resp = response.json()
        resp = json.loads(resp['text'])
        self.parse_resp(resp)
        cks = []
        for k, v in self.cookies.items():
            cks.append(f'{k}={v}')
        for k, v in self.session.cookies.get_dict().items():
            cks.append(f'{k}={v}')
        self.log.info('; '.join(cks))
        self.inc()
        self.performanceNow += int(time.time() * 1000 - self.startTs)
        self.px12280 = self.startTs2 + self.performanceNow

    def run(self):
        # self._init()
        self.seq = 0
        self.rsc = 1
        self._step_1()
        self.seq += 1
        # self._step_11()
        # time.sleep(1.5)

        self._step_2(True)
        # time.sleep(2)

        # self._step_2(False)
        #
        # # # if self.session.cookies.get_dict().get('_px2', None) == None:
        # # time.sleep(2)
        self._step_3()

        time.sleep(2)
        self._token()
        # self.add_header()

    def _init(self):
        cks = '_px2=eyJ1IjoiOGRjYjQ3NjAtODl2jYi0xMWVlLTkwMmUtODE4MTcxMjRjOTBlIiwidiI6IjhlOGIyMGMzLTg5Y2ItMTFlZS05YWI1LTAwMjc4Njk4ZmY1ZiIsInQiOjYyMDIzMzg4MDAwNCwiaCI6Ijk4NjYzMWNkZDBmNTBjMWE5NjZjYjgwOGNlNzFjYTJkMWNkYzc2MjdjYTc4MTBlZDVhODdmN2FiMzYzOGU1OTgifQ==;'

        # res = self.session.get(
        #     # self.target_url,
        #     'https://booking.flyfrontier.com/Flight/InternalSelect?o1=DEN&d1=LAS&dd1=2023-11-30&ADT=1&umnr=false&mon=true',
        #     headers={
        #         "authority": "www.flyfrontier.com",
        #         "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
        #         "accept-language": "en-US,en;q=0.9",
        #         "cache-control": "no-cache",
        #         "pragma": "no-cache",
        #         "sec-ch-ua": "\"Google Chrome\";v=\"117\", \"Not;A=Brand\";v=\"8\", \"Chromium\";v=\"117\"",
        #         "sec-ch-ua-mobile": "?0",
        #         "sec-ch-ua-platform": "\"macOS\"",
        #         "sec-fetch-dest": "document",
        #         "sec-fetch-mode": "navigate",
        #         "sec-fetch-site": "none",
        #         "sec-fetch-user": "?1",
        #         "upgrade-insecure-requests": "1",
        #         'cookie': cks,
        #         "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36",
        #     }, allow_redirects=False)

        res = requests.post(self.tlsUrl,
                            # response = requests.post('http://127.0.0.1:58000/tls/forward',
                            json=dict(
                                url='https://booking.flyfrontier.com/Flight/InternalSelect?o1=DEN&d1=LAS&dd1=2023-11-30&ADT=1&umnr=false&mon=true'
                                , headers={
                                    "authority": "www.flyfrontier.com",
                                    "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
                                    "accept-language": "en-US,en;q=0.9",
                                    "cache-control": "no-cache",
                                    "pragma": "no-cache",
                                    "sec-ch-ua": "\"Google Chrome\";v=\"117\", \"Not;A=Brand\";v=\"8\", \"Chromium\";v=\"117\"",
                                    "sec-ch-ua-mobile": "?0",
                                    "sec-ch-ua-platform": "\"macOS\"",
                                    "sec-fetch-dest": "document",
                                    "sec-fetch-mode": "navigate",
                                    "sec-fetch-site": "none",
                                    "sec-fetch-user": "?1",
                                    "upgrade-insecure-requests": "1",
                                    'cookie': cks,
                                    "user-agent": self.ua
                                }, method="GET", proxy=self.prox,
                                debug=True,
                                # ,allow_redirects=True

                            ))
        self.log.info(f"初始化请求 res {res.json()['status_code']}")
        self.params = {}
        # print(res.json())
        for k, v in res.json()['cookies'].items():
            self.params[k] = v
        self.log.info(f"init cookie {self.params}")
        with open('index.html', 'w') as f:
            f.write(res.text)

    def _uuid(self):
        # return str(uuid.uuid4())
        # return "b8a39670-7866-11ee-9655-63a4f05cd5d1"
        return ctxStep2.call('genUuid')

        r = ["00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0a", "0b", "0c", "0d", "0e", "0f", "10",
             "11",
             "12", "13", "14", "15", "16", "17", "18", "19", "1a", "1b", "1c", "1d", "1e", "1f", "20", "21", "22",
             "23",
             "24", "25", "26", "27", "28", "29", "2a", "2b", "2c", "2d", "2e", "2f", "30", "31", "32", "33", "34",
             "35",
             "36", "37", "38", "39", "3a", "3b", "3c", "3d", "3e", "3f", "40", "41", "42", "43", "44", "45", "46",
             "47",
             "48", "49", "4a", "4b", "4c", "4d", "4e", "4f", "50", "51", "52", "53", "54", "55", "56", "57", "58",
             "59",
             "5a", "5b", "5c", "5d", "5e", "5f", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6a",
             "6b",
             "6c", "6d", "6e", "6f", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7a", "7b", "7c",
             "7d",
             "7e", "7f", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8a", "8b", "8c", "8d", "8e",
             "8f",
             "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9a", "9b", "9c", "9d", "9e", "9f", "a0",
             "a1",
             "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "aa", "ab", "ac", "ad", "ae", "af", "b0", "b1", "b2",
             "b3",
             "b4", "b5", "b6", "b7", "b8", "b9", "ba", "bb", "bc", "bd", "be", "bf", "c0", "c1", "c2", "c3", "c4",
             "c5",
             "c6", "c7", "c8", "c9", "ca", "cb", "cc", "cd", "ce", "cf", "d0", "d1", "d2", "d3", "d4", "d5", "d6",
             "d7",
             "d8", "d9", "da", "db", "dc", "dd", "de", "df", "e0", "e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8",
             "e9",
             "ea", "eb", "ec", "ed", "ee", "ef", "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "fa",
             "fb",
             "fc", "fd", "fe", "ff"]
        bs = 0
        ys = [random.randint(10, 255) for _ in range(6)]
        # random.shuffle(ys)
        Gs = random.randint(1100, 9999)
        Ws = 0
        s = Gs
        h = get_timestamp()
        # h = 1701250281709
        d = bs + 1
        m = int(h - Ws + (d - bs) / 1e4)

        Ws = h
        bs = d
        Gs = s
        f = []
        u = 0
        # (1e4 * (268435455 & (f + 122192928e5)) + s) % 4294967296
        h += 122192928e5
        h = int(h)
        p = (1e4 * (268435455 & h) + 0) % 4294967296
        # p = 4180087664
        f[:3] = int(p).to_bytes(4, byteorder='big')
        Q = int(h / 4294967296 * 1e4) & 268435455
        # Q = 32386116
        f.append(unsinged_right_shift(Q, 8) & 255)
        f.append(255 & Q)
        f.append(unsinged_right_shift(Q, 24) & 15 | 16)
        f.append(unsinged_right_shift(Q, 16) & 255)
        # s = 6488
        f.append(unsinged_right_shift(s, 8) | 128)
        f.append(255 & s)
        for i in ys:
            f.append(i)
        # print(f)
        # 18992390-8912-11ee-a2e1-b3b33c4f608f
        # 70e50290-8911-11ee-bc61-f92af0d8127e
        # f = [112,229,2,144,137,17,17,238,188,97,249,42,240,216,18,126]
        res = [r[f[0]], r[f[1]], r[f[2]], r[f[3]], '-', r[f[4]], r[f[5]], '-', r[f[6]], r[f[7]], '-', r[f[8]],
               r[f[9]],
               '-',
               r[f[10]], r[f[11]], r[f[12]], r[f[13]], r[f[14]], r[f[15]]]
        return ''.join(res)

    def _step_1(self):
        t1 = int(time.time() * 1000)

        t2 = t1 + random.randint(5, 30)
        self.startTs = t1
        self.startTs2 = t2
        self.performanceNow = random.randint(5000, 6600)
        self.px12280 = self.startTs2 + self.performanceNow
        self.uuid = self._uuid()
        data = [{"t": "PX12095",
                 "d": {"PX11645": self.target_url, "PX12207": 0, "PX12458": "MacIntel", "PX11902": 0,
                       "PX11560": self.performanceNow, "PX12248": 3600, "PX11385": t1, "PX12280": t2,
                       "PX11496": self.uuid, "PX12564": None, "PX12565": -1,
                       # "PX11379": True
                       }}]
        self.do_collector(data)

    def encrypt(self, data, param):
        n = bytearray()
        if isinstance(data, str):
            bytess = data.encode()
        else:
            bytess = data
        for i in bytess:
            n.append(i ^ param)
        return n

    def _gen_pc(self, t1, e):
        # self.log.info(f'genpc t: {t}')
        # self.log.info(f'genpc e: {e}')
        # return ctxPC.call('genPc', t1,e)
        # r = requests.post('http://127.0.0.1:3001', data={
        #     't':t1,
        #     'e':e
        # })
        # print(r.text)
        # return r.text
        h = hmac.new(t1.encode('utf-8'), e.encode('utf-8'), hashlib.md5)
        t = h.hexdigest()
        # pc1
        e = ""
        b = ""
        for i in t:
            a = ord(i)
            if a >= 48 and a <= 57:
                e += i
            else:
                b += str(a % 10)

        r = e + b
        a2 = ""
        for i in range(0, len(r), 2):
            a2 += r[i]
        return a2

    def _token(self):
        # cks = []
        # for k, v in self.session.cookies.get_dict().items():
        #     cks.append(f'{k}={v}')
        # # resp = requests.post('http://127.0.0.1:59001/akamai/gen', json={
        # self.prox = f'http://user-uni001-region-us-sessid-{random.randint(1000, 5000)}-sesstime-5-keep-true:q39CEBTs5A5YQXor@pr.roxlabs.cn:4600'
        # self.prox = f'http://unfflcc:76cc14-47b8dd-1f8ace-827836-0c740e@usa.rotating.proxyrack.net:{random.randint(10000, 13500)}'
        cks = []
        s = set()
        # for k, v in self.cookies.items():
        #     if k not in s:
        #         cks.append(f'{k}={v}')
        #         s.add(k)
        for k, v in self.session.cookies.get_dict().items():
            cks.append(f'{k}={v}')
            s.add(k)
        url = 'https://booking.flyfrontier.com/Flight/InternalSelect?o1=DEN&d1=LAS&dd1=2023-11-30&ADT=1&umnr=false&mon=true'
        response = requests.post(self.tlsUrl,
                                 # response = requests.post('http://127.0.0.1:58000/tls/forward',
                                 json=dict(url=url, headers={
                                     "authority": "booking.flyfrontier.com",
                                     "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
                                     "accept-language": "en-US,en;q=0.9",
                                     "cache-control": "no-cache",
                                     "pragma": "no-cache",
                                     "sec-ch-ua": "\"Google Chrome\";v=\"117\", \"Not;A=Brand\";v=\"8\", \"Chromium\";v=\"117\"",
                                     "sec-ch-ua-mobile": "?0",
                                     "sec-ch-ua-platform": "\"macOS\"",
                                     "sec-fetch-dest": "document",
                                     "sec-fetch-mode": "navigate",
                                     "sec-fetch-site": "none",
                                     "sec-fetch-user": "?1",
                                     "upgrade-insecure-requests": "1",
                                     "user-agent": self.ua,
                                     "cookie": '; '.join(cks)
                                 }, method="GET", proxy=self.prox,
                                           debug=True
                                           , allow_redirects=True

                                           ))
        response = response.json()
        # print(response)
        # if response['status_code'] == 302:
        #     print(response['text'])
        # else:
        #     with open('index.html', 'w') as f:
        #         f.write(response['text'])

        # self.session.cookies.update(
        #     response['cookies']
        # )
        if response['status_code'] != 403:
            self.log.success(f"请求结果 {response['status_code']}")
            self.add_header()
        else:
            self.log.error(f"请求结果 {response['status_code']}")

    def _step_2(self, nn):

        self.log.info(self.uuid)
        self.log.info(f'performanceNow {self.performanceNow}')
        # sid, vid,ts, num1 ,num2,str1,  uuid
        # data_str = ctxStep2.call('genPayload2', self.target_url, self.sid, self.vid, self.ts, self.num1, self.num2,
        #                          self.str1, self.uuid,
        #                          self.startTs, self.startTs2, self.performanceNow, self.px12280, nn)
        # data_str =
        # data = json.loads(data_str)
        p = PxEnv(self.pxEnv, self.target_url, self.sid, self.vid, self.ts, self.num1, self.num2,
                  self.str1, self.uuid,
                  self.startTs, self.startTs2, self.performanceNow, self.px12280)
        data = [p.get_px11590()]
        # data_str2 = ctxStep2.call('genPayload3', self.target_url, self.sid, self.vid, self.ts, self.num1, self.num2,
        #                          self.str1, self.uuid,
        #                          self.startTs, self.startTs2, nn)
        # data2 = json.loads(data_str2)
        # data.extend(data2)

        self.do_collector(data)

    def _decode_resp(self):
        a = int(self.tag.replace('v', '').replace('.', ''))
        return a % 128

    def _step_11(self):
        data = [{"t": "PX12167", "d": {"PX11648": True}}]

        self.do_collector(data)

    def update_sid_vid(self, data: dict):
        if self.session.cookies.get_dict().get('_pxhd', None) != None:
            data.update({
                'pxhd': self.session.cookies.get_dict().get('_pxhd', None)
            })
        if self.vid != "":
            data.update({
                'vid': self.vid
            })
        if self.cs != "":
            data.update({
                'cs': self.cs
            })
        if self.cts != "":
            data.update({
                'cts': self.cts
            })
        if self.sid != "":
            data.update({
                'sid': self.sid
            })
        return data

    def _step_3(self):
        self.log.info(f'performanceNow {self.performanceNow}')
        # sid, vid,ts, num1 ,num2,str1,  uuid
        # genPayload4(url, sid, vid, ts, num1, num2, str1, uuid, startTs, startTs2, performanceNow, px11280, n)

        # data_str = ctxStep2.call('genPayload4', self.target_url, self.sid, self.vid, self.ts, self.num1,
        #                          self.num2,
        #                          self.str1, self.uuid,self.startTs, self.startTs2, self.performanceNow, self.px12280)
        p = PxEnv(self.pxEnv, self.target_url, self.sid, self.vid, self.ts, self.num1, self.num2,
                  self.str1, self.uuid,
                  self.startTs, self.startTs2, self.performanceNow, self.px12280)
        data = [
            p.get_px12123(),

            p.get_px11891(),
            p.get_px11547()]
        self.do_collector(data)

    def parse_resp(self, resp):
        if 'ob' in resp:
            cookies = self.encrypt(base64.b64decode(resp['ob'].encode()), self._decode_resp()).decode()
            cks = cookies.split('~~~~')
            self.log.info(f'len:: {len(cks)}')
            self.log.info(json.dumps(cks, indent=True))
            for i in cks:
                tmp = i.split('|')
                if tmp[0] == 'o111ooo1':
                    self.ts = tmp[1]
                if tmp[0] == 'o111oooo':
                    self.num1 = int(tmp[1])
                if tmp[0] == '111o1o':
                    self.num2 = tmp[1]

                if tmp[0] == '1oooo1':
                    self.str1 = tmp[1]
                if tmp[0] == 'o1oo1o':
                    self.vid = tmp[1]
                    self.cookies.update({
                        '_pxvid': self.vid
                    })
                    self.session.cookies.update({
                        '_pxvid': self.vid
                    })

                if tmp[0] == 'o11o11':
                    self.sid = tmp[1]
                if tmp[0] == '11o111':
                    self.cs = tmp[1]
                if tmp[0] == 'o11o11oo':
                    self.cts = tmp[1]
                    self.cookies.update({
                        'pxcts': self.cts
                    })
                    self.session.cookies.update({
                        'pxcts': self.cts
                    })

                if 'pxde' in i:
                    self.cookies.update({
                        '_pxde': tmp[3]
                    })
                    self.session.cookies.update({
                        '_pxde': tmp[3]
                    })
                elif '_px2' in i:
                    self.cookies.update({
                        '_px2': tmp[3]
                    })
                    self.session.cookies.update({
                        '_px2': tmp[3]
                    })
                    self.log.info(f'px2_decode {base64.b64decode(tmp[3].encode()).decode()}')
                # elif '31536000' in i:
                #     self.cookies.update({
                #         '_pxvid': tmp[1]
                #     })

        else:
            for i in resp['do']:
                tmp = i.split('|')
                print(len(tmp), tmp)
                if len(tmp) == 6 and tmp[1] in ['_px', '_px3', '_pxde']:
                    self.session.cookies.update({
                        tmp[1]: tmp[3]
                    })
                elif len(tmp) in [3, 4] and tmp[1] in ['cts', 'vid']:
                    self.session.cookies.update({
                        tmp[0]: tmp[1]
                    })

    def add_header(self):
        cks = []
        s = set()
        # for k, v in self.cookies.items():
        #
        #     if k not in s:
        #         cks.append(f'{k}={v}')
        #         s.add(k)

        for k, v in self.session.cookies.get_dict().items():
            cks.append(f'{k}={v}')
            s.add(k)
        print('; '.join(cks))

        headers = {
            "authority": "booking.flyfrontier.com",
            "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
            "accept-language": "en-US,en;q=0.9",
            "user-agent": self.ua,
            "cookie": '; '.join(cks)
        }
        uri = 'http://ymx-lcc.unififi.com/header/add'
        # uri = 'http://52.52.23.116/header/add'
        # proxy = f'http://unfflcc:76cc14-47b8dd-1f8ace-827836-0c740e@usa.rotating.proxyrack.net:{int(random.randint(10000, 11149))}'
        # proxy = 'http://unfflcc:76cc14-47b8dd-1f8ace-827836-0c740e@usa.rotating.proxyrack.net:10042'
        # proxy = 'http://user-unifflcc-region-us:q39CEBTs5A5YQXor@pr.roxlabs.cn:4600'
        brush_name = 'py1'
        r = requests.post(uri, json={
            'brush_fromto': 'LAS-BOS',
            'brush_fromdate': '2023-05-26',
            'brush_header': headers,
            'brush_proxy': self.prox,
            'brush_mode': 'shopping',
            'brush_name': brush_name,
            'brush_type': 'cookieF9',
        })
        self.log.info(f'添加接口 {r.text}')


if __name__ == '__main__':
    url = "https://booking.flyfrontier.com/Flight/InternalSelect?o1=DEN&d1=LAS&dd1=2023-11-30&ADT=1&umnr=false&mon=true"
    url = "https://www.flyfrontier.com/"
    while True:
        try:
            px = PxBypass(url)
            t1 = '''[{"t":"PX11590","d":{"PX11431":1701248155479,"PX12454":6371,"PX11701":"12286920904220322039","PX11529":34342085,"PX11555":4294705152,"PX11833":38986980,"PX11840":"Wed Nov 29 2023 16:55:55 GMT+0800 (中国标准时间)","PX12573":"621b88ff","PX11804":"a56be5c777767beda5f582d45e16dc35","PX12118":"cljfp6u0mf32013votgg","PX11746":"a3daefaf50543816dd162c6d116f4ac6","PX11371":"d2315a8c810c532d63e8287e70a97513","PX12501":"7a4c9311535c9112550cf9422b924c68","PX12169":1,"PX11902":1,"PX11560":8180,"PX11332":1701248155141,"PX12248":3600,"PX11385":1701248154916,"PX12280":1701248160983,"PX11496":"1b024930-8e95-11ee-ae67-53932ce066fc","PX12588":"unknown","PX12555":{"plugext":{"0":{"f":"internal-pdf-viewer","n":"PDF Viewer"},"1":{"f":"internal-pdf-viewer","n":"Chrome PDF Viewer"},"2":{"f":"internal-pdf-viewer","n":"Chromium PDF Viewer"},"3":{"f":"internal-pdf-viewer","n":"Microsoft Edge PDF Viewer"},"4":{"f":"internal-pdf-viewer","n":"WebKit built-in PDF"}},"plugins_len":5},"PX12583":{"smd":{"ok":true,"ex":false}},"PX12582":3,"PX12587":false,"PX12330":"109|66|66|70|80","PX11705":111,"PX11938":true,"PX11602":true,"PX12021":"false","PX12421":"false","PX12124":1,"PX11609":1,"PX12291":"","PX11881":["app","csi","loadTimes"],"PX12207":0,"PX11538":2,"PX11984":"TypeError: Cannot read properties of None (reading '0')\n    at he (https://client.px-cloud.net/PXVb73hTEg/main.min.js:1136:13)\n    at Zo (https://client.px-cloud.net/PXVb73hTEg/main.min.js:3320:22)\n    at Eo (https://client.px-cloud.net/PXVb73hTEg/main.min.js:2892:23)\n    at https://client.px-cloud.net/PXVb73hTEg/main.min.js:3265:9","PX11645":"https://www.flyfrontier.com/","PX11597":[],"PX12023":"","PX11337":false,"PX12544":true,"PX12589":"succeeded","PX11524":true,"PX11843":1920,"PX11781":1080,"PX12121":1920,"PX12128":1055,"PX12387":"1920X1080","PX12003":24,"PX11380":24,"PX11494":906,"PX12411":853,"PX12443":0,"PX12447":0,"PX11533":true,"PX12079":false,"PX12278":true,"PX11694":false,"PX12294":false,"PX12514":true,"PX12515":"TypeError: Cannot read properties of undefined (reading 'width')","PX12516":"webkit","PX12517":33,"PX12518":false,"PX12545":false,"PX12593":false,"PX12595":"AudioData.SVGAnimatedAngle.SVGMetadataElement","PX12069":["Chrome PDF Viewer","Chromium PDF Viewer","Microsoft Edge PDF Viewer","PDF Viewer","WebKit built-in PDF"],"PX12286":5,"PX11576":true,"PX12318":true,"PX11384":true,"PX11886":true,"PX11583":"en-US","PX12458":"MacIntel","PX11681":["en-US"],"PX11754":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36","PX12037":true,"PX11390":-480,"PX11621":8,"PX11657":1,"PX12081":"Gecko","PX11908":"20030107","PX12314":"5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36","PX11829":true,"PX11464":true,"PX12054":2,"PX11821":"Netscape","PX11479":"Mozilla","PX11674":true,"PX12241":400,"PX11372":false,"PX11683":1.5,"PX11561":"3g","PX11877":true,"PX12100":true,"PX12506":"arm","PX12507":"64","PX12509":false,"PX12510":"","PX12511":"macOS","PX12512":"13.5.0","PX12513":"117.0.5938.149","PX12548":true,"PX12578":{},"PX12579":{"support":true,"status":{"effectiveType":"3g","rtt":400,"downlink":1.5,"saveData":false}},"PX12508":[{"brand":"Google Chrome","version":"117"},{"brand":"Not;A=Brand","version":"8"},{"brand":"Chromium","version":"117"}],"PX12549":true,"PX11539":"831efc5e","PX11528":"","PX12271":"10207b2f","PX11849":"10207b2f","PX12464":"90e65465","PX11356":true,"PX12426":true,"PX11791":true,"PX11517":true,"PX12520":true,"PX12524":"4YC14YCd4YCd4YCV4YCe4YCX4YGS5J256aus7r266YaI5oCR7r27","PX12527":"3207084bd110f1ac964863e23aa78e04","PX12260":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36","PX12249":false,"PX11897":"90e65465","PX12597":1,"PX11526":false,"PX11684":false,"PX11812":false,"PX12335":true,"PX12080":0,"PX11678":false,"PX11349":"visible","PX12397":false,"PX11387":0,"PX12150":1920,"PX12304":true,"PX11651":970,"PX11867":"missing","PX12254":true,"PX11540":true,"PX11548":false,"PX11446":true,"PX12550":1,"PX12431":0,"PX11991":10,"PX11837":34,"PX11632":0,"PX11409":9,"PX11508":"49e5084e","PX11452":"7c5f9724","PX12218":"65d826e0","PX12481":"a9269e00","PX11780":"50a5ec55","PX12551":"https:","PX12553":"Asia/Shanghai","PX12567":"w3c","PX12576":"screen","PX12594":false,"PX12566":false,"PX12571":"74d9c66","PX12581":"default","PX11303":false,"PX11515":false,"PX12133":false,"PX12340":false,"PX11738":false,"PX11723":false,"PX11389":false,"PX11839":false,"PX11460":false,"PX12102":false,"PX11378":false,"PX12317":false,"PX12564":null,"PX12565":-1,":993=29;2;?99;899;82":";882<38:3:>88:988:93"}}]'''
            # t1 = ''
            t2 = '1b024930-8e95-11ee-ae67-53932ce066fc:v8.7.2:317'
            # print(px._gen_pc(t1, t2))
            px.run()
            # while True:
            #     print(px._uuid())
        # except KeyError:
        #     pass
        except:
            traceback.print_exc()
        time.sleep(1)
