import random
import subprocess
import time
import requests
import json
import tls_client
from bson import ObjectId

from pymongo import MongoClient

# 连接MongoDB数据库
client = MongoClient('mongodb://lcc-spider:JIUsfhiad&^@18.144.59.80:27017/?authSource=admin&directConnection=true')
db = client.env

# 查询所有文档
result = db.env_shape.find()
data = {str(x['_id']): x['env'] for x in result}
print(result)
with open('env.json', 'w') as f:
    f.write(json.dumps(data))

envs = data.keys()

session = tls_client.Session(client_identifier='chrome_112', random_tls_extension_order=False)

# session = requests.session()
headers = {
    "Host": "jbrest.jetblue.com",
    "application-channel": "Desktop_Web",
    "sec-ch-ua-platform": "\"macOS\"",
    "sec-ch-ua-mobile": "?0",
    "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36",
    "booking-application-type": "NGB",
    "content-type": "application/json",
    "accept": "application/json",
    "origin": "https://www.jetblue.com",
    "sec-fetch-site": "same-site",
    "sec-fetch-mode": "cors",
    "sec-fetch-dest": "empty",
    "accept-language": "en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7"
}
for i in range(100):
    selectId = random.choice(list(envs))
    t1 = time.time()
    # 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_run.js', selectId], 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("执行js失败")
    r = json.loads(tmp)
    res = db.env_shape.update_one(
        {'_id': ObjectId(selectId)},
        {"$inc": {"used": 1}}
    )
    # r = {
    #     'X-1ItxWO9i-f': 'A7AKCbCJAQAAV93ahgnafaQIeEbvT-Ss7YkuAnwrNQi_E70IpAViSqhv3hLLAXL3RNiucirJwH9eCOfvosJeCA==',
    #     'X-1ItxWO9i-b': 'ewccp4',
    #     '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EL3vzVf9dMiWGkk4RjHro6mRw9x=yZieyP8IVI=zoxZ8fMZTxXWvovpYvOAaCfyDMSe8ULjqDeFTnKuUlnMF8u6mhDwwh3co1DllqO2h11cd=M05OE91yMdB9l3vm6dbw0=JvHCTEi1Y_=2GcUPinRqzx6D2Mzb483ML2exPLrf6Og4HJ5UhWqFP8U-KXYhMeeLIn64069bCv3Fv2yfuHaieVrw_sp59TlWWfohsm32fLB64Hbw6C9tBYOaw7s6zF-V5gj9K-cE6e-RceM6n7tYR6qSkv1RFsK0rhBiy0=EIsV2BvARaQoTx_DzF-CBRVOUbtlyCfe8lA3xePq=Jk-JqXpSEMmXYfWlngYAOe69EWudOxLtqL8FtJq91v0sc9xk1R7X=k=j01PTR-74qEzS=9vxsZqPJjIn2aM5Vl9vag2eSEsBbL_WK_W9Q7BGQPi=iWjtDV6HfZSJYJojo5QieDe4b0KMg_8lU75I2yiX=J9Us-ebslQO=kX9i=Lojz1ea30jYfjlQaYEP7WXeklBY6rnvyxTYia_=h7kMKcQiogZOyAoOyjwbBFFSGOczdwCmd9FrFT5nAd7vf2my-wmf3FK4BD-BEF=DUMT2zUfc6PIL3=ovazFqJjJ2kBnAT9hwayqw56eYZTaPZRL'
    # }

    headers.update(r)
    print(f'{(time.time() - t1) *1000:.3f}ms',len(headers['X-1ItxWO9i-a'.lower()]))
    print(selectId, headers['user-agent'])
    url = "https://jbrest.jetblue.com/lfs-rwb/outboundLFS"
    data = {
        "tripType": "oneWay",
        "from": "LAS",
        "to": "BOS",
        "depart": "2023-09-10",
        "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,
        "isDomestic": False
    }
    proxy = f'http://unfflcc:76cc14-47b8dd-1f8ace-827836-0c740e@usa.rotating.proxyrack.net:{int(random.randint(10000, 11149))}'
    # 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 = 'http://127.0.0.1:7890'
    session.proxies = {
        'http': proxy,
        'https': proxy,
    }
    print(proxy)
    response = session.post(url, headers=headers, json=data)

    # print(response.text)
    if response.status_code == 200:
        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'
        print(selectId, headers)
        r = requests.post(uri, json={
            'brush_fromto': 'LAS-BOS',
            'brush_fromdate': '2023-05-22',
            'brush_header': headers,
            'brush_proxy':proxy,
            'brush_mode':'shopping',
            'brush_name':'js',
            'brush_type':'headerB6',
        })
        print('添加成功')
    # time.sleep(3)
