import platform
import random
import re
import subprocess
import time

import loguru
import requests
import json
import tls_client
from bson import ObjectId
import hashlib
from pymongo import MongoClient
from loguru import logger




def md5(text):
    m = hashlib.md5()
    m.update(text.encode())
    return m.hexdigest()

# 连接MongoDB数据库
client = MongoClient('mongodb://lcc-spider:JIUsfhiad&^@18.144.59.80:27017/?authSource=admin&directConnection=true')
db = client.env
# 查询所有文档
# result = db.env_shape.find({'env.funcs' :{'$ne': None}})
# data = {str(x['_id']): x['env'] for x in result}
# print(result)
# with open('env.json', 'w', encoding='utf-8') as f:
#     f.write(json.dumps(data))

with open('../env.json', 'r', encoding='utf-8') as f:
    data = json.loads(f.read())
envs = data.keys()


# session = requests.session()
headers = {
    "authority": "www.southwest.com",
    "accept": "application/json, text/javascript, */*; q=0.01",
    "accept-language": "en,en-US;q=0.9,zh-CN;q=0.8,zh;q=0.7,ru;q=0.6",
    "cache-control": "no-cache",
    "content-type": "application/json",
    # "ee30zvqlwf-a": " ",
    # "ee30zvqlwf-b": "gvz0do",
    # "ee30zvqlwf-c": "AOAR0oCMAQAApK-krk2Gl_JSI-lbzuGznw7YtZJke2dXZwtLTFTezRvx0Uej",
    # "ee30zvqlwf-d": "ABaAhIDBCKGFgQGAAYIQgISigaIAwBGAzvpizi_33wdU3s0b8dFHowAAAABnMdsJAOsqoNESu_ugV9zA2xwwV9k",
    # "ee30zvqlwf-f": "A98m1YCMAQAAwNQ03hUQGOrndnBMQaLc9jFMpR1h8uWR87fOt3-0dfXRVwaoAaesQHiucgHcwH9eCOfvosJeCA==",
    # "ee30zvqlwf-z": "q",
    "origin": "https://www.southwest.com",
    "pragma": "no-cache",
    "referer": "https://www.southwest.com/air/booking/index.html?adultPassengersCount=1&adultsCount=1&departureDate=2023-12-22&departureTimeOfDay=ALL_DAY&destinationAirportCode=LAX&fareType=USD&from=LAS&int=HOMEQBOMAIR&originationAirportCode=LAS&passengerType=ADULT&promoCode=&reset=true&returnDate=&returnTimeOfDay=ALL_DAY&to=LAX&tripType=oneway&validate=true",
    "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": "empty",
    "sec-fetch-mode": "cors",
    "sec-fetch-site": "same-origin",
    "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",
    "x-api-key": "l7xx944d175ea25f4b9c903a583ea82a1c4c",
    "x-app-id": "air-booking",
    "x-channel-id": "southwest",
    # "x-swa-di-dtid": "a50401789d810e7f268df8a3962bcf33530d",
    # "x-swa-di-pid": "3267595951737995",
    # "x-swa-di-ue": "",
    # "x-swa-di-uid": "6dfca0d9c0ad5535bfe2af894a20f40da6f1",
    # "x-swa-di-usid": "62767314733efef966e64a062d8f09df2c5e",
    # "x-user-experience-id": "baca03fc-030a-4ef7-a68f-9532ebde8154"
}
# tlss = [ 'chrome_103', 'chrome_104', 'chrome_105', 'chrome_106',
#         'firefox_102', 'firefox_104'
        # Opera --> opera_89, opera_90
      # 'safari_15_3', 'safari_15_6_1', 'safari_16_0',
      #   'safari_ios_15_5', 'safari_ios_15_6', 'safari_ios_16_0',
      #  'safari_ios_15_6'
      #   ]


while True:
    # r = requests.get('http://ymx-lcc.unififi.com/header/task/pull/headerB6?brush_name=test')
    # if r.json()['status'] != 0:
    #     logger.debug(f'不需要刷值')
    #     time.sleep(10)
    #     continue
    logger.debug('开始刷值')
    selectId = random.choice(list(envs))
    lastHash = ''
    usedTime = 10
    success = 0
    total = 0
    code = open('src.js', 'r', encoding='utf-8').read()
    for i in range(30):
        try:
            # selectId = '55a8fe24a752595e774341d6'
            proxy = f'http://unfflcc:76cc14-47b8dd-1f8ace-827836-0c740e@usa.rotating.proxyrack.net:{int(random.randint(10000, 11149))}'
            # proxy = requests.post('http://ymx-lcc.unififi.com/proxy/get-proxy', json={'name':"B6", 'type':'shopping'}).json()['url']
            # proxy = f'http://ynfflcc2023.hotmail.com:gdcfh9@69.30.227.194:{random.randint(20001, 20250)}'
            # proxy = f'http://user-uni003-region-us-sessid-{random.randint(1000,5000)}-sesstime-5-keep-true:q39CEBTs5A5YQXor@pr.roxlabs.cn:4600'
            # proxy = f'http://unfflcc:76cc14-47b8dd-1f8ace-827836-0c740e@198.147.25.26:{int(random.randint(10000, 11149))}'
            # proxy = 'http://user-unifflcc-region-us:q39CEBTs5A5YQXor@pr.roxlabs.cn:4600'
            proxy = f'http://user-uni001-region-us-sessid-{random.randint(1000,50000)}-sesstime-5-keep-true:q39CEBTs5A5YQXor@pr.roxlabs.cn:4600'
            # proxy = f'http://uni00001_custom_zone_US_sid_{random.randint(67336718, 67336728)}_time_5:q39CEBTs5A@us.foxyip.com:7778'

            tlsV = f'chrome_{random.randint(105, 113)}'
            tlsV = 'chrome_117'
            session = tls_client.Session(tlsV)
            session.proxies = {
                'http': proxy,
                'https': proxy,
            }
            if platform.uname().system == 'Darwin':
                session.proxies = {
                    'http': 'http://127.0.0.1:8890',
                    'https': 'http://127.0.0.1:8890',
                }
            selectId = random.choice(list(envs))
            # selectId = 'a74b38e7115cf4d1b1f6976c'
            c = session.get('https://www.southwest.com/assets/app/scripts/swa-common.js', insecure_skip_verify=True).text
            m5 = md5(c)
            if m5 != lastHash and usedTime > 5:
                lastHash = m5
                usedTime = 0
                logger.debug('js变化')
                token = re.findall('nt"\),\["(.+?)",', c)[0]
                # db.token_shape.insert_one({
                #     '_id': token,
                #     'update_time': int(time.time() * 1000)
                # })
                code = open('src.js', 'r', encoding='utf-8').read()
                code1 = open('js_dom_run.js', 'r', encoding='utf-8').read()
                with open('src_run1.js', 'w', encoding='utf-8') as f:
                    with open('src_run1.js', 'w', encoding='utf-8') as f:
                        f.write(code + '\n\n' + c
                                +
                                ';;;\n\n' + '''
                                        if (randomEvent){
                        window.mouse_move(startx,starty,endx,endy)

                    }

                    var xhr = new XMLHttpRequest();
                    xhr.open('POST', "https://www.southwest.com/api/air-booking/v1/air-booking/page/air/booking/shopping", false);
                    xhr.send(`{\"tripType\":\"oneWay\",\"from\":\"ZLA\",\"to\":\"NAS\",\"depart\":\"2023-04-11\",\"cabin\":\"economy\",\"refundable\":false,\"dates\":{\"before\":\"3\",\"after\":\"3\"},\"pax\":{\"ADT\":1,\"CHD\":0,\"INF\":0,\"UNN\":0},\"redempoint\":false,\"pointsBreakup\":{\"option\":\"\",\"value\":0},\"isMultiCity\":false}`)
                    xhr.setRequestHeader('user-agent', ENV.navigatorparams.useragent)
                    print(JSON.stringify(xhr.headers))
                    _process.exit(0)
                                        '''
                                )
                with open('js_dom_run1.js', 'w', encoding='utf-8') as f:
                    f.write(code1 + '\n\n' + c)
            t1 = time.time()
            # token = list(db.token_shape.aggregate( [ { '$sample': { 'size': 1 } } ] ))[0]['_id']
            # r = requests.get('http://127.0.0.1:5000/getinfo').json()['message']
            # r = requests.get('http://127.0.0.1:3001').json()
            # p = subprocess.Popen(['node', 'js_dom_run1.js', selectId, '11'], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
            # p = subprocess.Popen(['node', 'src_run_chrome_105.js', selectId, '11', token], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
            # p = subprocess.Popen(['node', 'src_run_company_chrome.js', selectId, '11', token], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
            p = subprocess.Popen(['node', 'src_run1.js', selectId, '11', token], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE)
            output, err = p.communicate(timeout=10)
            tmp = ''
            if p.returncode == 0:
                tmp = output.decode().split('\n')[-2]
            else:
                raise Exception(selectId)
            r = json.loads(tmp)
            # res = db.env_shape.update_one(
            #     {'_id': ObjectId(selectId)},
            #     {"$inc": {"used": 1}}
            # )
            usedTime += 1

            headers.update(r)
            print(headers)
            # headers = r
            logger.info(f"success:{success}  total:{total}  {(time.time() - t1) *1000:.3f}ms {len(headers['Ee30zvqlwf-A'.lower()])} {selectId} {headers['user-agent']}")
            # logger.info(f"success:{success}  proxy: {proxy}  token: {token}")
            url = "https://www.southwest.com/api/air-booking/v1/air-booking/page/air/booking/shopping"
            data = {
                "originationAirportCode": "LAS",
                "destinationAirportCode": "LAX",
                "departureDate": "2023-12-03",
                "departureTimeOfDay": "ALL_DAY",
                "returnTimeOfDay": "ALL_DAY",
                "adultPassengersCount": "1",
                "tripType": "oneway",
                "fareType": "USD",
                "passengerType": "ADULT",
                "adultsCount": "1",
                "int": "HOMEQBOMAIR",
                "reset": "true",
                "returnDate": "",
                "application": "air-booking",
                "site": "southwest"
            }
            #
            # # session = requests.Session()
            #
            response = session.post(url, headers=headers,json=data)
            status_code = response.status_code

            # response = requests.post('http://52.52.23.116/tls/forward',
            #              json=dict(url=url, headers=headers, method="POST",data=json.dumps(data), proxy=proxy, debug=True
            #                        , allow_redirects=True
            #                        ))
            # status_code = response.json()['status_code']
            # text = response.json()['text']
            logger.info(f'tls:{tlsV} proxy:{proxy}  res:: {status_code}')
            total += 1
            # print(text)
            # if status_code != 403:
            # res = db.env_shape.update_one(
            #     {'_id': ObjectId(selectId)},
            #     {"$inc": {"success": 1}}
            # )
            # proxy = requests.post('http://ymx-lcc.unififi.com/proxy/get-proxy', json={
            #     'type':'headerB6'
            # })
            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'
            r = requests.post(uri, json={
                'brush_fromto': 'LAS-BOS',
                'brush_fromdate': '2023-05-26',
                'brush_header': headers,
                'brush_proxy': proxy,
                'brush_mode': 'shopping',
                'brush_name': 'ts1',
                'brush_type': 'cookieWN',
            })
            success += 1
            logger.success(f'添加成功 {success}')
            # time.sleep(3)
        except Exception as e:
            print(e)
    time.sleep(10)
