1058 lines
41 KiB
Python
1058 lines
41 KiB
Python
import os.path
|
||
import random
|
||
import time
|
||
import uuid
|
||
import threading
|
||
from concurrent.futures.thread import ThreadPoolExecutor
|
||
|
||
# import requests
|
||
from curl_cffi import requests
|
||
import traceback
|
||
import json
|
||
from urllib.parse import urlencode, urlparse, parse_qs, unquote, quote
|
||
from 酒店任务拿交 import get_one_task, upload_one_task, cancel_one_task
|
||
import newsetting as ten
|
||
|
||
tent = ten.All_Setting(host='192.168.5.5', port=3306, db='mt_hotel')
|
||
tent2 = ten.All_Setting(host='183.6.7.91', port=33017, db='headers_project')
|
||
# proxy = {"http": None, "https": None}
|
||
import pymysql
|
||
from datetime import datetime
|
||
from typing import Dict, Any, Optional
|
||
|
||
import sys
|
||
# 本地出签(Node 补环境跑小程序 jsguard),实现在 mjz\小程序逆向\AI代码\小程序mtgsig.py
|
||
sys.path.insert(0, r'C:\Users\mjz\Desktop\python\mjz\小程序逆向\AI代码')
|
||
from 小程序mtgsig import get_mtgsig,get_h5_mtgsig_pure
|
||
|
||
# 城市坐标:代理出口城市 -> (lat, lng),从 project_proxy.citylist 按城市名取(level=2 为城市级)
|
||
|
||
THREAD_NUM = 1 # 线程池大小
|
||
BATCH = time.strftime('%Y%m%d%H%M%S') # 本进程批次号
|
||
city_lock = threading.Lock() # 多线程选包时按城市加锁
|
||
running_cities = set() # 正在跑的城市
|
||
|
||
# owl-wxapp util.traceid:uuid_v1 两半倒序异或 → 有符号 int64;node/clockseq 进程内固定
|
||
_trace_node = None
|
||
_trace_clockseq = None
|
||
_trace_last_msecs = 0
|
||
_trace_last_nsecs = 0
|
||
|
||
|
||
def gen_m_traceid():
|
||
# 对齐小程序 @dp/owl-wxapp,每次请求重新生成 M-TRACEID
|
||
global _trace_node, _trace_clockseq, _trace_last_msecs, _trace_last_nsecs
|
||
if _trace_node is None or _trace_clockseq is None:
|
||
seed = [0] * 16
|
||
r = 0
|
||
for t in range(16):
|
||
if (t & 3) == 0:
|
||
r = int(random.random() * 4294967296) & 0xffffffff
|
||
seed[t] = (r >> ((t & 3) << 3)) & 255
|
||
if _trace_node is None:
|
||
_trace_node = [1 | seed[0], seed[1], seed[2], seed[3], seed[4], seed[5]]
|
||
if _trace_clockseq is None:
|
||
_trace_clockseq = 16383 & ((seed[6] << 8) | seed[7])
|
||
msecs = int(time.time() * 1000)
|
||
nsecs = _trace_last_nsecs + 1
|
||
dt = msecs - _trace_last_msecs + (nsecs - _trace_last_nsecs) / 10000.0
|
||
clockseq = _trace_clockseq
|
||
if dt < 0:
|
||
clockseq = (clockseq + 1) & 16383
|
||
if dt < 0 or msecs > _trace_last_msecs:
|
||
nsecs = 0
|
||
_trace_last_msecs = msecs
|
||
_trace_last_nsecs = nsecs
|
||
_trace_clockseq = clockseq
|
||
msecs2 = msecs + 12219292800000
|
||
tl = int((1e4 * (msecs2 & 0x0fffffff) + nsecs) % 4294967296)
|
||
tmh = int(msecs2 / 4294967296 * 1e4) & 0x0fffffff
|
||
b = [0] * 16
|
||
b[0] = (tl >> 24) & 255
|
||
b[1] = (tl >> 16) & 255
|
||
b[2] = (tl >> 8) & 255
|
||
b[3] = tl & 255
|
||
b[4] = (tmh >> 8) & 255
|
||
b[5] = tmh & 255
|
||
b[6] = ((tmh >> 24) & 15) | 16
|
||
b[7] = (tmh >> 16) & 255
|
||
b[8] = (clockseq >> 8) | 128
|
||
b[9] = clockseq & 255
|
||
for j in range(6):
|
||
b[10 + j] = _trace_node[j]
|
||
e = ''.join(format(x, '02x') for x in b)
|
||
left, right = e[:16], e[16:]
|
||
xor_hex = ''.join(
|
||
format(int(left[15 - t], 16) ^ int(right[15 - t], 16), 'x')
|
||
for t in range(16)
|
||
)
|
||
val = int(xor_hex, 16)
|
||
if len(xor_hex) > 15 and int(xor_hex[0], 16) >= 8:
|
||
return str(val - (1 << 64))
|
||
return str(val)
|
||
|
||
|
||
def set_m_traceid(headers):
|
||
# 只改抓包里本来就有的 key(大小写原样保留);没有就不写;多个就都更新成同一个新值
|
||
keys = [k for k in headers.keys() if k.lower() == 'm-traceid']
|
||
if not keys:
|
||
return None
|
||
tid = gen_m_traceid()
|
||
for k in keys:
|
||
headers[k] = tid
|
||
return tid
|
||
|
||
|
||
def clean_and_insert_hotel_booking(
|
||
raw_data: Dict[str, Any],
|
||
) -> Dict[str, Any]:
|
||
"""
|
||
清洗酒店预订数据并插入数据库
|
||
|
||
Args:
|
||
raw_data: API返回的原始数据
|
||
|
||
Returns:
|
||
{'success': bool, 'message': str, 'id': int or None}
|
||
"""
|
||
|
||
# 1. 检查响应状态
|
||
if raw_data.get('code') != 0:
|
||
return {
|
||
'success': False,
|
||
'message': f"API返回错误: {raw_data.get('message', '未知错误')}",
|
||
'id': None
|
||
}
|
||
|
||
data = raw_data.get('data', {})
|
||
if not data:
|
||
return {
|
||
'success': False,
|
||
'message': '数据为空',
|
||
'id': None
|
||
}
|
||
|
||
# 2. 数据清洗
|
||
def clean_string(value: Any, max_length: int = None) -> Optional[str]:
|
||
"""清洗字符串字段"""
|
||
if value is None:
|
||
return None
|
||
result = str(value).strip()
|
||
if max_length and len(result) > max_length:
|
||
result = result[:max_length]
|
||
return result if result else None
|
||
|
||
def clean_int(value: Any, default: int = None) -> Optional[int]:
|
||
"""清洗整数字段"""
|
||
if value is None:
|
||
return default
|
||
try:
|
||
return int(value)
|
||
except (ValueError, TypeError):
|
||
return default
|
||
|
||
def clean_date(value: Any) -> Optional[str]:
|
||
"""清洗日期字段"""
|
||
if value is None:
|
||
return None
|
||
try:
|
||
# 验证日期格式
|
||
datetime.strptime(str(value), '%Y-%m-%d')
|
||
return str(value)
|
||
except ValueError:
|
||
return None
|
||
|
||
# 3. 清洗后的数据
|
||
cleaned_data = {
|
||
'hotel_id': clean_string(data.get('hotelId'), 20),
|
||
'city_id': clean_string(data.get('cityId'), 10),
|
||
'hotel_name': clean_string(data.get('hotelName'), 100),
|
||
'hotel_address': clean_string(data.get('hotelAddress'), 200),
|
||
'city_name': clean_string(data.get('cityName'), 50),
|
||
'check_in_date': clean_date(data.get('checkInDate')),
|
||
'check_out_date': clean_date(data.get('checkOutDate')),
|
||
'unique_id': clean_string(data.get('uniqueId'), 100),
|
||
'time_left': clean_int(data.get('timeLeft')),
|
||
'hotel_star': clean_string(data.get('hotelStar'), 20),
|
||
'selected_city': clean_string(data.get('selectedCity'), 50),
|
||
'area_type': clean_string(data.get('areaType'), 50),
|
||
'area_name': clean_string(data.get('areaName'), 100),
|
||
'level': clean_int(data.get('level'), 0)
|
||
}
|
||
|
||
# 4. 验证必填字段
|
||
required_fields = ['hotel_id', 'city_id', 'hotel_name', 'check_in_date', 'check_out_date']
|
||
for field in required_fields:
|
||
if not cleaned_data.get(field):
|
||
return {
|
||
'success': False,
|
||
'message': f'必填字段缺失: {field}',
|
||
'id': None
|
||
}
|
||
try:
|
||
# 使用 INSERT ... ON DUPLICATE KEY UPDATE 处理重复
|
||
sql = """
|
||
INSERT INTO hotel_task (
|
||
hotel_id, city_id, hotel_name, hotel_address, city_name,
|
||
check_in_date, check_out_date, unique_id, time_left,
|
||
hotel_star, selected_city, area_type, area_name, level
|
||
) VALUES (
|
||
%(hotel_id)s, %(city_id)s, %(hotel_name)s, %(hotel_address)s, %(city_name)s,
|
||
%(check_in_date)s, %(check_out_date)s, %(unique_id)s, %(time_left)s,
|
||
%(hotel_star)s, %(selected_city)s, %(area_type)s, %(area_name)s, %(level)s
|
||
)
|
||
ON DUPLICATE KEY UPDATE
|
||
hotel_id = VALUES(hotel_id),
|
||
city_id = VALUES(city_id),
|
||
hotel_name = VALUES(hotel_name),
|
||
hotel_address = VALUES(hotel_address),
|
||
city_name = VALUES(city_name),
|
||
check_in_date = VALUES(check_in_date),
|
||
check_out_date = VALUES(check_out_date),
|
||
time_left = VALUES(time_left),
|
||
hotel_star = VALUES(hotel_star),
|
||
selected_city = VALUES(selected_city),
|
||
area_type = VALUES(area_type),
|
||
area_name = VALUES(area_name),
|
||
level = VALUES(level)
|
||
"""
|
||
|
||
tent.write_data(sql, (cleaned_data,))
|
||
return {
|
||
'success': True,
|
||
'message': '插入成功',
|
||
'id': None,
|
||
}
|
||
|
||
except pymysql.IntegrityError as e:
|
||
return {
|
||
'success': False,
|
||
'message': f'数据完整性错误: {str(e)}',
|
||
'id': None
|
||
}
|
||
except pymysql.Error as e:
|
||
return {
|
||
'success': False,
|
||
'message': f'数据库错误: {str(e)}',
|
||
'id': None
|
||
}
|
||
|
||
|
||
def parse_url(url: str) -> dict:
|
||
"""
|
||
解析URL,返回基础URL和参数字典
|
||
|
||
Args:
|
||
url: 完整的URL字符串
|
||
|
||
Returns:
|
||
dict: 包含 'url' 和 'params' 的字典
|
||
"""
|
||
parsed = urlparse(url)
|
||
|
||
# 基础URL(不含查询参数)
|
||
base_url = f"{parsed.scheme}://{parsed.netloc}{parsed.path}"
|
||
|
||
# 解析查询参数
|
||
# parse_qs 返回的值是列表,这里转换为单值(如果只有一个值)
|
||
params_raw = parse_qs(parsed.query, keep_blank_values=True)
|
||
params = {}
|
||
|
||
for key, value in params_raw.items():
|
||
# 如果列表只有一个元素,直接取值;否则保留列表
|
||
params[key] = value[0] if len(value) == 1 else value
|
||
|
||
# return {
|
||
# "url": base_url,
|
||
# "params": params
|
||
# }
|
||
return (base_url, params)
|
||
|
||
|
||
def build_url(base_url, params):
|
||
"""
|
||
将基础URL和参数字典拼接成完整的URL
|
||
"""
|
||
# doseq=True 会将列表展开为多个同名参数
|
||
query_string = urlencode(params, doseq=True)
|
||
full_url = f"{base_url}?{query_string}"
|
||
return full_url
|
||
|
||
|
||
def get_sign_new(url, data, dfpid, mtg_origin):
|
||
headers = {"content-type": "application/json", "token": "jksdfhiownefopwef902fsdf"}
|
||
|
||
body = {
|
||
"mtg_origin": mtg_origin,
|
||
"url": url,
|
||
"data": data,
|
||
"dfpid": dfpid,
|
||
"method": "POST"}
|
||
|
||
# url = "http://124.222.120.219:18003/hz_wm_jym_1008"
|
||
url = 'http://8.138.127.139:10063/newmtgsig'
|
||
req = requests.post(url, headers=headers, json=body, proxies={'http': None, 'https': None}, verify=False).text
|
||
return req
|
||
|
||
|
||
def get_sign_new1(url, data, dfpid, mtg_origin,openId):
|
||
headers = {"content-type": "application/json", "token": "test_sdfio23923ojbedfojgbouqgew4r32dds"}
|
||
body = {
|
||
"mtg_origin":mtg_origin,
|
||
"url": url,
|
||
"data": data,
|
||
"dfpid": dfpid,
|
||
"method": "POST",
|
||
"open_id": openId,# 微信的open_id
|
||
}
|
||
# url = "http://124.222.120.219:18003/hz_wm_jym_1008"
|
||
url = 'http://129.211.12.35:18003/minipro_mt_0206'
|
||
req = requests.post(url, headers=headers, json=body, proxies={'http': None, 'https': None}, verify=False).text
|
||
print(req)
|
||
return req
|
||
|
||
def get_sign_new_get(url, data, dfpid, mtg_origin):
|
||
headers = {"content-type": "application/json", "token": "jksdfhiownefopwef902fsdf"}
|
||
|
||
body = {
|
||
"mtg_origin": mtg_origin,
|
||
"url": url,
|
||
"data": data,
|
||
"dfpid": dfpid,
|
||
"method": "GET"}
|
||
|
||
# url = "http://124.222.120.219:18003/hz_wm_jym_1008"
|
||
url = 'http://8.138.127.139:10063/newmtgsig'
|
||
req = requests.post(url, headers=headers, json=body, proxies={'http': None, 'https': None}, verify=False).text
|
||
return req
|
||
|
||
|
||
def get_sign_new1_get(url, data, dfpid, mtg_origin,openId):
|
||
headers = {"content-type": "application/json", "token": "test_sdfio23923ojbedfojgbouqgew4r32dds"}
|
||
body = {
|
||
"mtg_origin":mtg_origin,
|
||
"url": url,
|
||
"data": data,
|
||
"dfpid": dfpid,
|
||
"method": "GET",
|
||
"open_id": openId,# 微信的open_id
|
||
}
|
||
# url = "http://124.222.120.219:18003/hz_wm_jym_1008"
|
||
url = 'http://129.211.12.35:18003/minipro_mt_0206'
|
||
req = requests.post(url, headers=headers, json=body, proxies={'http': None, 'https': None}, verify=False).text
|
||
print(req)
|
||
return req
|
||
|
||
def get_Datatext(dataq):
|
||
str1 = ''
|
||
for i in dataq:
|
||
key, value = i, dataq[i]
|
||
str2 = f'{key}={value}&'
|
||
str1 = str1 + str2
|
||
data = str1[0:-1]
|
||
return data
|
||
|
||
|
||
def same_type(old, value):
|
||
# 跟抓包里原来的 JSON 类型保持一致
|
||
if isinstance(old, bool):
|
||
return str(value)
|
||
if isinstance(old, int):
|
||
return int(value)
|
||
if isinstance(old, float):
|
||
return float(value)
|
||
return str(value)
|
||
|
||
|
||
def put_city(obj, key, city_id):
|
||
# 包里没有、或是 -1/0,就保持原样;正常城市 id 才跟着当前城市变
|
||
if key not in obj:
|
||
return
|
||
if str(obj[key]) in ('-1', '0'):
|
||
return
|
||
obj[key] = same_type(obj[key], city_id)
|
||
|
||
|
||
def put_coord(obj, key, value):
|
||
# 包里没有、或是 0,就保持原样;原来是正常坐标才跟着绑定城市变
|
||
if key not in obj:
|
||
return
|
||
if str(obj[key]) in ('0', '0.0'):
|
||
return
|
||
obj[key] = same_type(obj[key], value)
|
||
|
||
def save_suggest_store(res, hotel_name, city_id, suggest_id):
|
||
# 已有 poi 就更新字段,没有再新增。suggest 没有的字段不覆盖旧值
|
||
hotels = {}
|
||
for item in res['data']:
|
||
poi_id = str(item['poiIdStr'])
|
||
if poi_id == '0':
|
||
continue
|
||
row = {'poi_id': poi_id, 'poi_name': item['word'] or ''}
|
||
prop = item['propagateData']
|
||
if isinstance(prop, dict):
|
||
if 'contentTransparent' in prop and prop['contentTransparent']:
|
||
row['content_transparent'] = prop['contentTransparent']
|
||
if 'content' in prop and prop['content']:
|
||
row['content'] = prop['content']
|
||
if 'poiType' in prop and prop['poiType'] not in (None, ''):
|
||
row['poi_type'] = str(prop['poiType'])
|
||
if 'mysteryBoxCrossActivityId' in prop and prop['mysteryBoxCrossActivityId'] not in (None, ''):
|
||
row['mystery_box_cross_activity_id'] = str(prop['mysteryBoxCrossActivityId'])
|
||
hotels[poi_id] = row
|
||
for item in res['stidItems']:
|
||
poi_id = str(item['poiIdStr'])
|
||
if poi_id == '0':
|
||
continue
|
||
content_transparent = item['propagateData']['data']['contentTransparent']
|
||
if poi_id not in hotels:
|
||
hotels[poi_id] = {'poi_id': poi_id, 'poi_name': ''}
|
||
if 'content_transparent' not in hotels[poi_id] and content_transparent:
|
||
hotels[poi_id]['content_transparent'] = content_transparent
|
||
rows = [row for row in hotels.values() if 'content_transparent' in row]
|
||
if not rows:
|
||
print('suggest 没有可入库的店')
|
||
return
|
||
in_sql = ','.join(["'%s'" % row['poi_id'] for row in rows])
|
||
exist_rows = tent.get_shoppingmalls('SELECT poi_id FROM hotel_suggest_store WHERE poi_id IN (%s)' % in_sql)
|
||
exists = set(str(row[0]) for row in exist_rows)
|
||
insert_sql = '''
|
||
INSERT INTO hotel_suggest_store
|
||
(poi_id, poi_name, content_transparent, content, poi_type, mystery_box_cross_activity_id, keyword, city_id, suggest_id, batch, source, search_time)
|
||
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,NOW())
|
||
'''
|
||
update_full_sql = '''
|
||
UPDATE hotel_suggest_store
|
||
SET poi_name=%s, content_transparent=%s, content=%s, poi_type=%s, keyword=%s, city_id=%s, suggest_id=%s, batch=%s, source=%s, search_time=NOW()
|
||
WHERE poi_id=%s
|
||
'''
|
||
update_ct_sql = '''
|
||
UPDATE hotel_suggest_store
|
||
SET poi_name=%s, content_transparent=%s, keyword=%s, city_id=%s, suggest_id=%s, batch=%s, source=%s, search_time=NOW()
|
||
WHERE poi_id=%s
|
||
'''
|
||
update_box_sql = '''
|
||
UPDATE hotel_suggest_store
|
||
SET mystery_box_cross_activity_id=%s
|
||
WHERE poi_id=%s
|
||
'''
|
||
insert_data = []
|
||
update_full = []
|
||
update_ct = []
|
||
update_box = []
|
||
for row in rows:
|
||
poi_id = row['poi_id']
|
||
if poi_id in exists:
|
||
if 'mystery_box_cross_activity_id' in row:
|
||
update_box.append((row['mystery_box_cross_activity_id'], poi_id))
|
||
if 'content' in row and 'poi_type' in row:
|
||
update_full.append((
|
||
row['poi_name'], row['content_transparent'], row['content'], row['poi_type'],
|
||
hotel_name, city_id, suggest_id, BATCH, 'suggest', poi_id,
|
||
))
|
||
else:
|
||
update_ct.append((
|
||
row['poi_name'], row['content_transparent'],
|
||
hotel_name, city_id, suggest_id, BATCH, 'suggest', poi_id,
|
||
))
|
||
continue
|
||
insert_data.append((
|
||
poi_id,
|
||
row['poi_name'],
|
||
row['content_transparent'],
|
||
row['content'] if 'content' in row else None,
|
||
row['poi_type'] if 'poi_type' in row else None,
|
||
row['mystery_box_cross_activity_id'] if 'mystery_box_cross_activity_id' in row else None,
|
||
hotel_name,
|
||
city_id,
|
||
suggest_id,
|
||
BATCH,
|
||
'suggest',
|
||
))
|
||
if insert_data:
|
||
tent.write_data(insert_sql, insert_data)
|
||
if update_full:
|
||
tent.update_data_many(update_full_sql, update_full)
|
||
if update_ct:
|
||
tent.update_data_many(update_ct_sql, update_ct)
|
||
if update_box:
|
||
tent.update_data_many(update_box_sql, update_box)
|
||
print('suggest 入库 新增%s 更新%s' % (len(insert_data), len(update_full) + len(update_ct)))
|
||
|
||
|
||
def get_content_transparent(hotel_name, hotel_id, city_id, city_gps, proxy, with_propagate=False):
|
||
# 这家店在 hotel_suggest_store 里字段齐就直接用,缺了再打 suggest 并回写
|
||
hotel_name = hotel_name.replace(' ', '')
|
||
sql = f'''
|
||
SELECT content_transparent, content, poi_type, mystery_box_cross_activity_id, keyword
|
||
FROM hotel_suggest_store WHERE poi_id='{hotel_id}' ORDER BY id DESC LIMIT 1
|
||
'''
|
||
rows = list(tent.get_shoppingmalls(sql))
|
||
if rows:
|
||
# content_transparent, content, poi_type, mystery_box, keyword = rows[0]
|
||
# if not with_propagate and content_transparent:
|
||
# print('命中 hotel_suggest_store,跳过搜索推荐:', hotel_id, keyword)
|
||
# return content_transparent, None
|
||
# if with_propagate and content_transparent and content and poi_type not in (None, ''):
|
||
# if str(poi_type).isdigit():
|
||
# poi_type_value = int(poi_type)
|
||
# else:
|
||
# poi_type_value = poi_type
|
||
# propagate = {
|
||
# 'content': content,
|
||
# 'contentTransparent': content_transparent,
|
||
# 'poiType': poi_type_value,
|
||
# }
|
||
# if mystery_box not in (None, ''):
|
||
# propagate['mysteryBoxCrossActivityId'] = mystery_box
|
||
# print('命中 hotel_suggest_store,跳过搜索推荐:', hotel_id, keyword)
|
||
# return propagate, None
|
||
print('hotel_suggest_store 字段不全,继续打 suggest:', hotel_id)
|
||
# 从 hotel_suggest_hd 取一条搜索推荐包;详情请求仍用 hotel_hd 里的包
|
||
sql = '''
|
||
SELECT id,json_data,prox,city,mt_traceid FROM hotel_suggest_hd WHERE title LIKE '%酒店搜索推荐%' and is_ok is NULL
|
||
'''
|
||
rows = list(tent2.get_shoppingmalls(sql))
|
||
if not rows:
|
||
print('hotel_suggest_hd 没有可用包')
|
||
return None, None
|
||
random.shuffle(rows)
|
||
ind, hd, prox, city, mt_traceid = rows[0]
|
||
url, headers, data = json.loads(hd)
|
||
base_url, params = parse_url(url)
|
||
version_name = params['version_name']
|
||
params['keyword'] = hotel_name
|
||
params['cityid'] = city_id
|
||
params['locateCityId'] = city_id
|
||
params['locatecityid'] = city_id
|
||
params['antiRepCityId'] = city_id
|
||
url = build_url(base_url, params)
|
||
print('suggest_url:', url)
|
||
set_m_traceid(headers)
|
||
mtg_origin = eval(headers['mtgsig'])
|
||
dfpid = mtg_origin['a3']
|
||
if 'openId' in headers:
|
||
openId = headers['openId']
|
||
else:
|
||
openId = headers['openid']
|
||
headers['mtgsig'] = get_sign_new1_get(url, '', dfpid, mtg_origin, openId)
|
||
# headers['mtgsig'] = get_mtgsig(url, '', headers['mtgsig'], openId, 'GET')
|
||
try:
|
||
# mitm 抓包是 TLSv1.3 + HTTP/1.1,不是 Chrome 的 h2
|
||
response = requests.get(url, headers=headers, proxies=proxy, http_version='v1')
|
||
except Exception as e:
|
||
proxy_url = urlparse(proxy['http']) if proxy else None
|
||
proxy_ip = '%s:%s' % (proxy_url.hostname, proxy_url.port) if proxy_url else None
|
||
print('suggest 请求失败 hotel_id=%s proxy_ip=%s: %s' % (hotel_id, proxy_ip, e))
|
||
traceback.print_exc()
|
||
return None, None
|
||
print('suggest:', response.status_code, response.text[:])
|
||
if response.status_code == 403:
|
||
sql = f'''
|
||
UPDATE hotel_suggest_hd SET is_ok=403 WHERE `id`={ind}
|
||
'''
|
||
tent2.update_data(sql)
|
||
return None, None
|
||
if response.status_code == 418 or '您的网络好像不太给力,请稍后再试' in response.text:
|
||
sql = f'''
|
||
UPDATE hotel_suggest_hd SET is_ok=418 WHERE `id`={ind}
|
||
'''
|
||
tent2.update_data(sql)
|
||
return None, None
|
||
if "Unauthorized" in response.text[:500]:
|
||
sql = f'''
|
||
UPDATE hotel_suggest_hd SET is_ok=401 WHERE `id`={ind}
|
||
'''
|
||
tent2.update_data(sql)
|
||
return None, None
|
||
if response.status_code != 200:
|
||
print('suggest 非200:', response.status_code)
|
||
return None, None
|
||
try:
|
||
res = response.json()
|
||
except Exception as e:
|
||
print('suggest JSON 解析失败 hotel_id=%s: %s' % (hotel_id, e))
|
||
traceback.print_exc()
|
||
sql = f'''
|
||
UPDATE hotel_suggest_hd SET is_ok=403 WHERE `id`={ind}
|
||
'''
|
||
tent2.update_data(sql)
|
||
return None, None
|
||
if res['code'] != 0:
|
||
print('suggest 返回错误:', res['msg'])
|
||
return None, None
|
||
sql = f'''
|
||
UPDATE hotel_suggest_hd SET current_count=current_count+1,req_count=req_count+1 WHERE `id`={ind}
|
||
'''
|
||
tent2.update_data(sql)
|
||
save_suggest_store(res, hotel_name, city_id, ind)
|
||
if with_propagate:
|
||
for x in res['data']:
|
||
if str(x['poiIdStr']) == str(hotel_id):
|
||
return x['propagateData'], version_name
|
||
print('suggest 未命中该店:', hotel_id)
|
||
return '', version_name
|
||
# for x in res['data']:
|
||
# if str(x['poiIdStr']) != str(hotel_id):
|
||
# continue
|
||
# prop = x['propagateData']
|
||
# if isinstance(prop, dict) and prop['contentTransparent']:
|
||
# return prop['contentTransparent'], version_name
|
||
# prepay 的 p 在 stidItems
|
||
for i in res['stidItems']:
|
||
if str(i['poiIdStr']) == str(hotel_id):
|
||
return i['propagateData']['data']['contentTransparent'], version_name
|
||
print('suggest 未命中该店:', hotel_id)
|
||
return '', version_name
|
||
|
||
|
||
class hotel_run:
|
||
USER = "thzn-datagram0001"
|
||
PWD = "thzn-datagram0001"
|
||
VENDOR = "mt-datagram"
|
||
# clientid = uuid.uuid4().int
|
||
clientid = "666"
|
||
|
||
costSourceChannel = "1"
|
||
input = ""
|
||
keyword = ""
|
||
mtShareId = ""
|
||
fromOffline = "false"
|
||
flagshipFilter = "1"
|
||
needShowNewDiscInfo = "false"
|
||
lat = "31.820953"
|
||
lng = "117.222201"
|
||
ci = "20"
|
||
channelCityId = "20"
|
||
hotelCustomGpsStatus = "0"
|
||
specialDealHotelScene = "true"
|
||
riskPlatform = "13"
|
||
channelSelectCityId = "20"
|
||
appletVersionName = "9.51.4"
|
||
appletAppId = "wxde8ac0a21135c07d"
|
||
specAttributionChannel = ""
|
||
magicMemberCode = "1102,1103"
|
||
|
||
# proxy = {"http": None,"https": None}
|
||
def __init__(self):
|
||
self.proxy_list = self.get_prox()
|
||
print(self.proxy_list)
|
||
self.city_gps = self.get_city_gps()
|
||
print('城市坐标数:', len(self.city_gps))
|
||
|
||
def run_shelf(self, url, params, headers, data, prox, task):
|
||
clientid = task['data']['cityName'].replace('市', '')
|
||
if prox:
|
||
self.proxy = json.loads(prox)
|
||
# 城市 id、坐标用 citylist。没有这个城市就留包里的原值
|
||
# gps_city_id = self.get_city_id(self.bound_city)
|
||
# if not gps_city_id:
|
||
# print(f"城市 {self.bound_city} 在 area_info 查不到 cityId,跳过")
|
||
# return -1
|
||
city_row = self.city_gps.get(self.bound_city)
|
||
# if not city_gps:
|
||
# print(f"城市 {self.bound_city} 在 citylist 无坐标,跳过")
|
||
# return -1
|
||
suggest_city_id = task['data']['cityId']
|
||
city_gps = None
|
||
if city_row:
|
||
suggest_city_id = city_row['city_id']
|
||
city_gps = (city_row['lat'], city_row['lng'])
|
||
result = clean_and_insert_hotel_booking(task)
|
||
hotel_info = task["data"]
|
||
print(result)
|
||
print(task)
|
||
print(type(task['data']))
|
||
# 有 citylist 就改城市 id 和坐标。入住离店按任务日期,0 点
|
||
business = data['requestParams'][0]['businessParams']
|
||
data['poiId'] = same_type(data['poiId'], task['data']['hotelId'])
|
||
business['poiId'] = same_type(business['poiId'], task['data']['hotelId'])
|
||
start = int(datetime.strptime(task['data']['checkInDate'], '%Y-%m-%d').timestamp() * 1000)
|
||
end = int(datetime.strptime(task['data']['checkOutDate'], '%Y-%m-%d').timestamp() * 1000)
|
||
business['start'] = same_type(business['start'], start)
|
||
business['end'] = same_type(business['end'], end)
|
||
business['hourRoomStart'] = same_type(business['hourRoomStart'], start)
|
||
business['hourRoomEnd'] = same_type(business['hourRoomEnd'], start)
|
||
# task_city_id = task['data']['cityId']
|
||
if city_row:
|
||
put_city(business, 'cityId', suggest_city_id)
|
||
put_city(business, 'channelCityId', suggest_city_id)
|
||
put_city(business, 'userCityId', suggest_city_id)
|
||
put_city(business, 'appCityId', suggest_city_id)
|
||
# put_city(business, 'gps_cityid', suggest_city_id)
|
||
# put_city(business, 'gpsCityid', suggest_city_id)
|
||
# put_city(business, 'locateCityId', suggest_city_id)
|
||
# put_city(business, 'locatecityid', suggest_city_id)
|
||
put_coord(business, 'lat', city_row['lat'])
|
||
put_coord(business, 'lng', city_row['lng'])
|
||
put_coord(data, 'lat', float(city_row['lat']))
|
||
put_coord(data, 'lng', float(city_row['lng']))
|
||
# put_city(data, 'locateCityId', suggest_city_id)
|
||
# put_city(data, 'locatecityid', suggest_city_id)
|
||
put_city(params, 'ci', suggest_city_id)
|
||
data['clientRequestTime'] = int(time.time() * 1000)
|
||
|
||
suggest_propagate, _ = get_content_transparent(
|
||
task['data']['hotelName'], task['data']['hotelId'], suggest_city_id, city_gps, self.proxy,
|
||
with_propagate=True)
|
||
if suggest_propagate is None:
|
||
print(f"酒店 {task['data']['hotelId']} suggest 请求失败,跳过(不取消任务)")
|
||
return -2
|
||
if not suggest_propagate:
|
||
print(f"酒店 {task['data']['hotelId']} suggest 搜不到,取消任务")
|
||
cancel_resp = cancel_one_task(self.VENDOR, self.USER, self.PWD, clientid, task, 30)
|
||
print('取消任务:', cancel_resp)
|
||
return -3
|
||
if 'poiType' in business and suggest_propagate['poiType'] not in (None, ''):
|
||
business['poiType'] = same_type(business['poiType'], suggest_propagate['poiType'])
|
||
propagate_json = json.dumps(suggest_propagate, separators=(',', ':'), ensure_ascii=False)
|
||
data['propagateData'] = quote(propagate_json, safe='')
|
||
params['propagateData'] = propagate_json
|
||
|
||
data2 = json.dumps(data, separators=(',', ':'), ensure_ascii=False)
|
||
new_url = build_url(url, params)
|
||
if 'openId' in headers:
|
||
openId = headers['openId']
|
||
else:
|
||
openId = headers['openid']
|
||
# shelf 先本地出签,解不开再走云端;出签用抓包里的原始 mtgsig 字符串
|
||
signed = get_mtgsig(new_url, data2, headers['mtgsig'], openId, 'POST', sys={'brand': 'redmi','model': '2510ERA8BC'})
|
||
# signed = get_mtgsig(new_url, data2, headers['mtgsig'], openId, 'POST')
|
||
# mtg_origin = eval(headers['mtgsig'])
|
||
# dfpid = mtg_origin['a3']
|
||
# signed = get_sign_new1(new_url, data2, dfpid, mtg_origin, openId)
|
||
headers['mtgsig'] = signed
|
||
set_m_traceid(headers)
|
||
|
||
headers.pop('Content-Length', None) # body 已重建,长度让 curl_cffi 按实际重算
|
||
response = requests.post(new_url, headers=headers, data=data2, proxies=self.proxy, verify=False, http_version='v1')
|
||
|
||
print("response.text", '-' * 50, response.text[:])
|
||
if '您的网络好像不太给力,请稍后再试' in response.text:
|
||
cancel_resp = cancel_one_task(self.VENDOR, self.USER, self.PWD, clientid, task, 30)
|
||
print('取消任务:', cancel_resp)
|
||
return 418
|
||
if "Unauthorized" in response.text[:500]:
|
||
cancel_resp = cancel_one_task(self.VENDOR, self.USER, self.PWD, clientid, task, 30)
|
||
print('取消任务:', cancel_resp)
|
||
return 401
|
||
if response.status_code != 200 or (response.text or '')[:1] != '{':
|
||
print('shelf 失败 http=%s,取消任务' % response.status_code)
|
||
cancel_resp = cancel_one_task(self.VENDOR, self.USER, self.PWD, clientid, task, 30)
|
||
print('取消任务:', cancel_resp)
|
||
return 403
|
||
res = response.json()
|
||
if res['code'] != 0:
|
||
print('shelf code=%s,取消任务' % res['code'])
|
||
cancel_resp = cancel_one_task(self.VENDOR, self.USER, self.PWD, clientid, task, 30)
|
||
print('取消任务:', cancel_resp)
|
||
return 403
|
||
upload_one_task(self.VENDOR, self.USER, self.PWD, clientid, task, res)
|
||
# 从响应里提取 traceId,存到 self 供外部回写 hotel_hd
|
||
self.last_trace_id = self._find_trace_id(res)
|
||
sql = '''
|
||
INSERT INTO `hotel_json`
|
||
(json_data, poi_id, city_id, hotel_name, city_name, check_in_date, check_out_date)
|
||
VALUES (%s, %s, %s, %s, %s, %s, %s)
|
||
'''
|
||
tent.write_data(sql, ((
|
||
json.dumps(res), hotel_info.get('hotelId'), hotel_info.get('cityId'), hotel_info.get('hotelName'),
|
||
hotel_info.get('cityName'), hotel_info.get('checkInDate'), hotel_info.get('checkOutDate')),))
|
||
return 1
|
||
|
||
def run_prepayList(self, url, params, headers, prox, task):
|
||
clientid = task['data']['cityName'].replace('市', '')
|
||
if prox:
|
||
self.proxy = json.loads(prox)
|
||
# 城市 id、坐标用 citylist。没有这个城市就留包里的原值
|
||
# gps_city_id = self.get_city_id(self.bound_city)
|
||
# if not gps_city_id:
|
||
# print(f"城市 {self.bound_city} 在 area_info 查不到 cityId,跳过")
|
||
# return -1
|
||
city_row = self.city_gps.get(self.bound_city)
|
||
# if not city_gps:
|
||
# print(f"城市 {self.bound_city} 在 citylist 无坐标,跳过")
|
||
# return -1
|
||
suggest_city_id = task['data']['cityId']
|
||
city_gps = None
|
||
if city_row:
|
||
suggest_city_id = city_row['city_id']
|
||
city_gps = (city_row['lat'], city_row['lng'])
|
||
result = clean_and_insert_hotel_booking(task)
|
||
hotel_info = task["data"]
|
||
print(result)
|
||
params['poiId'] = task['data']['hotelId']
|
||
eight = 8 * 60 * 60 * 1000
|
||
start = str(int(datetime.strptime(task['data']['checkInDate'], '%Y-%m-%d').timestamp() * 1000) + eight)
|
||
end = str(int(datetime.strptime(task['data']['checkOutDate'], '%Y-%m-%d').timestamp() * 1000) + eight)
|
||
# start = int(datetime.strptime(task['data']['checkInDate'], '%Y-%m-%d').timestamp() * 1000) + eight
|
||
# end = int(datetime.strptime(task['data']['checkOutDate'], '%Y-%m-%d').timestamp() * 1000) + eight
|
||
params['start'] = start
|
||
params['end'] = end
|
||
# 没有 citylist 时留详情包原值
|
||
if city_row:
|
||
params['locateCityId'] = suggest_city_id
|
||
params['locatecityid'] = suggest_city_id
|
||
params['cityId'] = suggest_city_id
|
||
params['ci'] = suggest_city_id
|
||
params['channelCityId'] = suggest_city_id
|
||
params['channelSelectCityId'] = suggest_city_id
|
||
params['gps_cityid'] = suggest_city_id
|
||
params['lat'] = city_row['lat']
|
||
params['lng'] = city_row['lng']
|
||
content_transparent, suggest_version_name = get_content_transparent(
|
||
task['data']['hotelName'], task['data']['hotelId'], suggest_city_id, city_gps, self.proxy)
|
||
if content_transparent is None:
|
||
print(f"酒店 {task['data']['hotelId']} suggest 请求失败,跳过(不取消任务)")
|
||
return -2
|
||
if not content_transparent:
|
||
print(f"酒店 {task['data']['hotelId']} suggest 搜不到,取消任务")
|
||
cancel_resp = cancel_one_task(self.VENDOR, self.USER, self.PWD, clientid, task, 30)
|
||
print('取消任务:', cancel_resp)
|
||
return -3
|
||
params['propagateData'] = content_transparent
|
||
# params['propagateData'] = ''
|
||
# if suggest_version_name:
|
||
# params['version_name'] = suggest_version_name
|
||
new_url = build_url(url, params)
|
||
|
||
mtg_origin = eval(headers['mtgsig'])
|
||
dfpid = mtg_origin['a3']
|
||
if 'openId' in headers:
|
||
openId = headers['openId']
|
||
else:
|
||
openId = headers['openid']
|
||
headers['mtgsig'] = get_sign_new1_get(new_url, '', dfpid, mtg_origin,openId)
|
||
# headers['mtgsig'] = get_mtgsig(new_url, '', headers['mtgsig'], openId, 'GET')
|
||
set_m_traceid(headers)
|
||
|
||
# mitm 抓包是 TLSv1.3 + HTTP/1.1,不是 Chrome 的 h2
|
||
print(json.dumps([new_url, headers, '']))
|
||
input(456)
|
||
response = requests.get(new_url, headers=headers, proxies=self.proxy, verify=False, http_version='v1')
|
||
|
||
print(response.text[:])
|
||
if '您的网络好像不太给力,请稍后再试' in response.text:
|
||
print(json.dumps([new_url,headers,'']))
|
||
return 418
|
||
if "Unauthorized" in response.text[:500]:
|
||
return 401
|
||
res = response.json()
|
||
upload_one_task(self.VENDOR, self.USER, self.PWD, clientid, task, res)
|
||
self.last_trace_id = self._find_trace_id(res)
|
||
sql = '''
|
||
INSERT INTO `hotel_json`
|
||
(json_data, poi_id, city_id, hotel_name, city_name, check_in_date, check_out_date)
|
||
VALUES (%s, %s, %s, %s, %s, %s, %s)
|
||
'''
|
||
tent.write_data(sql, ((
|
||
json.dumps(res), hotel_info.get('hotelId'), hotel_info.get('cityId'), hotel_info.get('hotelName'),
|
||
hotel_info.get('cityName'), hotel_info.get('checkInDate'), hotel_info.get('checkOutDate')),))
|
||
return 1
|
||
|
||
def get_headers(self):
|
||
# 取一批可用抓包 headers,主循环随机挑一条跑
|
||
sql = '''
|
||
SELECT `id`,json_data,prox,city,mt_traceid FROM `hotel_hd` WHERE title LIKE '%美团酒店详情%' and is_ok is NULL and ((current_count<2 and phone_tag = '国内号') or (current_count<35 and phone_tag = '老港号'));
|
||
'''
|
||
sql = '''
|
||
SELECT `id`,json_data,prox,city,mt_traceid FROM `hotel_hd` WHERE title LIKE '%美团酒店详情%' and is_ok is NULL and id=20564;
|
||
'''
|
||
# sql = '''
|
||
# SELECT `id`,json_data,prox,city,mt_traceid FROM `hotel_hd` WHERE title LIKE '%美团酒店详情%' and ((is_ok != 403 and is_ok != 418 and is_ok != 401) or is_ok is null) and id=12635
|
||
# '''
|
||
headers = tent2.get_shoppingmalls(sql)
|
||
return headers
|
||
|
||
def run_one(self, items):
|
||
# 直接随机拿包;没城市/没 IP 就补上再用
|
||
items = list(items)
|
||
random.shuffle(items)
|
||
ind, hd, prox, city, mt_traceid = items[0]
|
||
if city:
|
||
city = city.replace('市', '')
|
||
|
||
# 没 IP:有城市先找同城,找不到就在带城市的代理里随机
|
||
if not prox:
|
||
matched = []
|
||
if city:
|
||
matched = [p for p in self.proxy_list if p[1] and (p[1] in city or city in p[1])]
|
||
if not matched:
|
||
matched = [p for p in self.proxy_list if p[1]]
|
||
if not matched:
|
||
print('代理池没有可用 IP,跳过')
|
||
return
|
||
pick = matched[random.randint(0, len(matched) - 1)]
|
||
prox = pick[0]
|
||
if not city:
|
||
city = pick[1]
|
||
|
||
# 没城市:按 IP 反查;反查不到就换一个带城市的代理
|
||
if not city:
|
||
matched = [p for p in self.proxy_list if p[0] == prox]
|
||
if matched:
|
||
city = matched[0][1]
|
||
else:
|
||
matched = [p for p in self.proxy_list if p[1]]
|
||
if not matched:
|
||
print('代理池没有可用城市,跳过')
|
||
return
|
||
pick = matched[random.randint(0, len(matched) - 1)]
|
||
prox = pick[0]
|
||
city = pick[1]
|
||
|
||
self.proxy = json.loads(prox)
|
||
# self.proxy = {"http": None, "https": None}
|
||
self.bound_city = city
|
||
|
||
task = get_one_task(self.VENDOR, self.USER, self.PWD, city, city)
|
||
print(task)
|
||
if not task:
|
||
print(city)
|
||
sql = f'''
|
||
UPDATE hotel_hd SET is_ok=0 WHERE `id`={ind}
|
||
'''
|
||
tent2.update_data(sql)
|
||
return -1
|
||
|
||
url, headers, data = json.loads(hd)
|
||
if isinstance(data, str) and '{' in data:
|
||
data = json.loads(data)
|
||
new_url, params = parse_url(url)
|
||
# M-TRACEID 在各请求函数里每次重新生成;这里只先记下库里旧值,成功后会用响应/新值回写
|
||
self.last_trace_id = mt_traceid
|
||
|
||
print(f"本次使用: 城市={self.bound_city}, proxy={self.proxy}")
|
||
|
||
try:
|
||
# 根据抓包 URL 分发到对应请求函数
|
||
if '/hotel/core/router/shelf' in new_url:
|
||
result = self.run_shelf(new_url, params, headers, data, None, task)
|
||
if result == -1:
|
||
return -1
|
||
if result in (-2, -3):
|
||
return
|
||
elif '/productapi/v3/prepayList' in new_url:
|
||
result = self.run_prepayList(new_url, params, headers, None, task)
|
||
if result == -1:
|
||
return -1
|
||
if result in (-2, -3):
|
||
return
|
||
else:
|
||
print(f"未知接口,跳过: {new_url}")
|
||
return
|
||
self.update_headers(result, ind, city, self.last_trace_id)
|
||
except Exception as e:
|
||
error_msg = f"""
|
||
{'=' * 50}
|
||
时间: {time.strftime('%Y-%m-%d %H:%M:%S')}
|
||
ID: {ind}
|
||
错误类型: {type(e).__name__}
|
||
错误信息: {str(e)}
|
||
详细堆栈:
|
||
{traceback.format_exc()}
|
||
{'=' * 50}
|
||
"""
|
||
print(error_msg)
|
||
if 'Expecting value: line 1 column 1 (char 0)' in str(e):
|
||
is_ok = 403
|
||
else:
|
||
is_ok = 0
|
||
self.update_headers(is_ok, ind, city, None)
|
||
|
||
def update_headers(self, is_ok, ind, city, mt_traceid):
|
||
# 成功只累计次数,失败写 is_ok 状态,proxy/city/traceId 都回填
|
||
if is_ok == 1:
|
||
sql = f'''
|
||
UPDATE hotel_hd SET current_count=current_count+1,req_count=req_count+1,prox='{json.dumps(self.proxy)}',city='{city}',mt_traceid='{mt_traceid}' WHERE `id`={ind}
|
||
'''
|
||
else:
|
||
sql = f'''
|
||
UPDATE hotel_hd SET is_ok={is_ok},prox='{json.dumps(self.proxy)}',city='{city}',mt_traceid='{mt_traceid}' WHERE `id`={ind}
|
||
'''
|
||
tent2.update_data(sql)
|
||
|
||
def _find_trace_id(self, obj):
|
||
"""递归找响应里第一个 traceId 值"""
|
||
if isinstance(obj, dict):
|
||
if 'traceId' in obj:
|
||
return str(obj['traceId'])
|
||
for v in obj.values():
|
||
r = self._find_trace_id(v)
|
||
if r:
|
||
return r
|
||
elif isinstance(obj, list):
|
||
for item in obj:
|
||
r = self._find_trace_id(item)
|
||
if r:
|
||
return r
|
||
return None
|
||
|
||
def get_city_id(self, city_name):
|
||
"""从 area_info 查美团 cityId,查不到返回 None"""
|
||
sql = f"SELECT cityId FROM area_crood.area_info WHERE cityName='{city_name}' and title like '%美团%' LIMIT 1"
|
||
rows = tent.get_shoppingmalls(sql)
|
||
if rows:
|
||
return rows[0][0]
|
||
return None
|
||
|
||
def get_city_gps(self):
|
||
sql = '''
|
||
SELECT name, lat, lng, mt_city_id FROM project_proxy.citylist WHERE level=2 and name is not null
|
||
'''
|
||
rows = tent2.get_shoppingmalls(sql)
|
||
return {r[0]: {'lat': str(r[1]), 'lng': str(r[2]), 'city_id': str(r[3])} for r in rows}
|
||
|
||
def get_prox(self):
|
||
sql = '''
|
||
SELECT prox_data,city FROM project_proxy.proxs_list WHERE channel ORDER BY RAND()
|
||
'''
|
||
prox_list = tent2.get_shoppingmalls(sql)
|
||
return prox_list
|
||
|
||
|
||
def pick_item(items):
|
||
# 优先挑一个当前没在跑的城市包;都占用了再退回无城市包
|
||
items = list(items)
|
||
random.shuffle(items)
|
||
with city_lock:
|
||
none_item = None
|
||
for j in items:
|
||
city_key = (j[3] or '').replace('市', '')
|
||
if not city_key:
|
||
if none_item is None:
|
||
none_item = j
|
||
continue
|
||
if city_key in running_cities:
|
||
continue
|
||
running_cities.add(city_key)
|
||
return j, city_key
|
||
if none_item is not None:
|
||
return none_item, ''
|
||
return None, None
|
||
|
||
|
||
def run_hotel():
|
||
ht = hotel_run()
|
||
items = ht.get_headers()
|
||
item, city_key = pick_item(items)
|
||
if item is None:
|
||
print('没有可用的详情包,跳过')
|
||
return
|
||
try:
|
||
ht.run_one([item])
|
||
finally:
|
||
if city_key:
|
||
with city_lock:
|
||
running_cities.discard(city_key)
|
||
# time.sleep(random.randint(2, 5))
|
||
# run2()
|
||
|
||
|
||
if __name__ == '__main__':
|
||
p = ThreadPoolExecutor(THREAD_NUM)
|
||
for i in range(1000):
|
||
p.submit(run_hotel)
|
||
time.sleep(1)
|
||
p.shutdown(wait=True)
|