import random
import subprocess
import time
import requests
import json
import tls_client
from bson import ObjectId
import hashlib
from pymongo import MongoClient

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()
# data = {str(x['_id']): x['env'] for x in result}
# print(result)
# with open('env.json', 'w') as f:
#     f.write(json.dumps(data))
with open('env.json', 'r') as f:
    data = json.loads(f.read())
envs = data.keys()


# session = requests.session()
headers = {
    "Host": "jbrest.jetblue.com",
    "application-channel": "Desktop_Web",
    "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",
    "accept-language": "en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7"
}
# 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'
      #   ]
lastHash = ''
usedTime = 10
code = open('src.js', 'r').read()
selectId = random.choice(list(envs))

for i in range(100):
    # selectId = 'a74b38e7115cf4d1b1f6976c'
    c = requests.get('https://www.jetblue.com/js/src/jb-74873.js').text
    m5 = md5(c)
    if m5 != lastHash and usedTime > 3:
        lastHash = m5
        usedTime = 0
        print('js变化')
        selectId = random.choice(list(envs))

        # with open('src_run1.js', 'w') as f:
        #     f.write(code + '\n\n' + c)
    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,
    p = subprocess.Popen(['node', 'src_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}}
    )
    usedTime += 1
#     r  =  {
#     "X-1ItxWO9i-b": "-xsyeom",
#     "sec-ch-ua": "\"Not/A)Brand\";v=\"99\", \"Google Chrome\";v=\"115\", \"Chromium\";v=\"115\"",
#     "accept-language": "en-US,en;q=0.9",
#     "X-1ItxWO9i-f": "AxzF9mOKAQAAu-M8Cs8kC-WTfg7mOQ6nX0-GNLW_F3LBQA2ulwiMXOo5L4hyAXL3RNgXTirJwH9eCOfvosJeCA==",
#     "application-channel": "Mobile_Web_iOS",
#     "sec-ch-ua-platform": "\"macOS\"",
#     "pragma": "no-cache",
#     "sec-ch-ua-mobile": "?0",
#     "X-1ItxWO9i-c": "AMBK9mOKAQAAANLpeAMbERfDqm7dksUxyF9_G4y5qHzaBOGncP5sh1AJ4kty",
#     "booking-application-type": "NGB",
#     "X-1ItxWO9i-d": "ABaAhIjBCKHFgQGAAYIQgISi0aIA5JmBzvpDzz8A_myHUAniS3IAAAAAH29cNgB9tpxxseHLkPFbvtmPsR-c",
#     "content-type": "application/json",
#     "accept": "application/json",
#     "X-1ItxWO9i-z": "q",
#     "cache-control": "no-cache",
#     "Referer": "https://www.jetblue.com/booking/flights?from=LGA&to=LAX&depart=2023-10-16&isMultiCity=false&noOfRoute=1&lang=en&adults=1&children=0&infants=0&sharedMarket=false&roundTripFaresFlag=false&usePoints=false",
#     "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36",
#     "api-version": "v3",
#     "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J97kd_W9m3B_ov5wBy_lMFN0s7KStNhitQI4Vj8mAdwT5KbYB2BUPba1lpJaDRtFi3D3LehNwGYtAa=baLoNjfId_RIBxmQKFWrIoCTDGoyUoJtwuaf6l=tzUugvcsPh68wRPRGI7UaXpxKRBEUegw7UYJKLCWQaaQ7OSuNjlIcdv9CeEsvms-4lm2c_lehpPBS_s0eGYQPa39x6jGzz2_unpUjeDcyOxuz_nwaiUzlku4ab7EG1D-iLxlmMzZKLZOEdAClTFaYqW9zEcsqgBv7y4GPyiWjmaq6qWf2mxjnC_GvuiLh=OrQNZJp-9fPvjYmrigSnjF5Og1ZFkjxJnWyLPget6x0Ded_3w_XrwaK_pzLdq_4mq-KYAp7vDx934p8fh6nUKXu9Zpaa_GWLQRwnoups=REKN0nYzP4xom8B9iB=l4hhGeQ2ctzQXiN=B5oDvmlv1UYgijRKQ299pCL16EvDElkaIdqDqAx27wMIVvgNw2xc9ZdKv4rOjpQTAk2eKfW=xTCAa8jrIoc6-Y2l3qnLb7CQjALCbWe3txU1=EZAO3z8PoCPyLryFWiAohPx"
# }

    headers.update(r)
    # headers = 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-05-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'
    tlsV = f'chrome_{random.randint(105,113)}'
    session = tls_client.Session(client_identifier=tlsV)
    session.proxies = {
        'http': proxy,
        'https': proxy,
    }
    print(tlsV, proxy)
    response = session.post(url, headers=headers, json=data)

    # print(response.text)
    print(response.status_code)
    if response.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'
        proxy = f'http://unfflcc:76cc14-47b8dd-1f8ace-827836-0c740e@usa.rotating.proxyrack.net:{int(random.randint(10000, 11149))}'

        print(selectId, headers)
        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':'js',
            'brush_type':'headerB6',
        })
        print('添加成功')
    # time.sleep(3)
