300 lines
11 KiB
Python
300 lines
11 KiB
Python
# shelf 组包+发送,逻辑从 酒店详情.py run_shelf 复制;不含领任务、suggest、入库
|
||
import copy
|
||
import json
|
||
import os
|
||
import random
|
||
import sys
|
||
import time
|
||
from datetime import datetime
|
||
from urllib.parse import parse_qs, quote, urlencode, urlparse
|
||
|
||
from curl_cffi import requests
|
||
|
||
import newsetting as ten
|
||
|
||
# ============ 配置区:改这里 ============
|
||
HD_ID = 18833 # hotel_hd 详情包 id
|
||
POI_ID = '193415547' # 酒店 poiId
|
||
CHECK_IN_DATE = '2026-11-21' # 入住 yyyy-mm-dd
|
||
CHECK_OUT_DATE = '2026-11-22' # 离店 yyyy-mm-dd
|
||
PROPAGATE_DATA = None # 整份 propagate dict;与 PROPAGATE_JSON 二选一
|
||
PROPAGATE_JSON = r'C:\Users\mjz\Desktop\python\mjz\6_酒店\酒店详情_测试_grok4.7_关键词propagate.json' # 文件里取与 POI_ID 匹配项的 propagateData
|
||
CITY_ID = '20' # 改城市时填写,三个都配齐才改包内城市/坐标;任一为 None 则留抓包原值
|
||
LAT = '23.1148'
|
||
LNG = '113.267874'
|
||
PROXY = {"http": "http://uuvg:uuvgt@2p3c.smart.51tcp.net:20644", "https": "http://uuvg:uuvgt@2p3c.smart.51tcp.net:20644"} # 不用代理就 None
|
||
# ============ 配置区结束 ============
|
||
|
||
tent2 = ten.All_Setting(host='183.6.7.91', port=33017, db='headers_project')
|
||
|
||
sys.path.insert(0, r'C:\Users\mjz\Desktop\python\mjz\小程序逆向\AI代码')
|
||
from 小程序mtgsig import get_mtgsig
|
||
|
||
# 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 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 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 get_hd_packet(hd_id):
|
||
# 从 hotel_hd 取指定 id 的详情包,只拿这一条;M-TRACEID 不发请求时写库值,走 set_m_traceid 自生成
|
||
sql = f'''
|
||
SELECT json_data FROM hotel_hd WHERE id={hd_id}
|
||
'''
|
||
rows = list(tent2.get_shoppingmalls(sql))
|
||
if not rows:
|
||
print('hotel_hd 没有这个 id 的包:', hd_id)
|
||
return None, None, None
|
||
hd = rows[0][0]
|
||
url, headers, data = json.loads(hd)
|
||
return url, headers, data
|
||
|
||
|
||
def load_propagate():
|
||
if PROPAGATE_DATA:
|
||
return PROPAGATE_DATA
|
||
if not PROPAGATE_JSON or not os.path.isfile(PROPAGATE_JSON):
|
||
print('请配置 PROPAGATE_DATA 或有效的 PROPAGATE_JSON')
|
||
return None
|
||
with open(PROPAGATE_JSON, encoding='utf-8') as f:
|
||
rows = json.load(f)
|
||
for row in rows:
|
||
if str(row.get('poiId')) == str(POI_ID):
|
||
return row['propagateData']
|
||
print('JSON 里没有 POI_ID=%s 的 propagateData' % POI_ID)
|
||
return None
|
||
|
||
|
||
def run_shelf_request(url, params, headers, data, suggest_propagate, poi_id, check_in, check_out, proxy, city_row=None):
|
||
data = copy.deepcopy(data)
|
||
params = copy.deepcopy(params)
|
||
headers = copy.deepcopy(headers)
|
||
# 有 citylist 就改城市 id 和坐标。入住离店按任务日期,0 点
|
||
business = data['requestParams'][0]['businessParams']
|
||
data['poiId'] = same_type(data['poiId'], poi_id)
|
||
business['poiId'] = same_type(business['poiId'], poi_id)
|
||
start = int(datetime.strptime(check_in, '%Y-%m-%d').timestamp() * 1000)
|
||
end = int(datetime.strptime(check_out, '%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)
|
||
if city_row:
|
||
suggest_city_id = city_row['city_id']
|
||
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)
|
||
|
||
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=proxy, verify=False, http_version='v1')
|
||
|
||
print("response.text", '-' * 50, response.text[:])
|
||
if '您的网络好像不太给力,请稍后再试' in response.text:
|
||
print('shelf 418')
|
||
return 418, response.text
|
||
if "Unauthorized" in response.text[:500]:
|
||
print('shelf 401')
|
||
return 401, response.text
|
||
if response.status_code != 200 or (response.text or '')[:1] != '{':
|
||
print('shelf 失败 http=%s' % response.status_code)
|
||
return response.status_code, response.text
|
||
res = response.json()
|
||
if res['code'] != 0:
|
||
print('shelf code=%s' % res['code'])
|
||
return 403, res
|
||
return 200, res
|
||
|
||
|
||
if __name__ == '__main__':
|
||
suggest_propagate = load_propagate()
|
||
if not suggest_propagate:
|
||
sys.exit(1)
|
||
url, headers, data = get_hd_packet(HD_ID)
|
||
if not url:
|
||
sys.exit(1)
|
||
if '/hotel/core/router/shelf' not in url:
|
||
print('详情包不是 shelf:', url[:120])
|
||
sys.exit(1)
|
||
if isinstance(data, str) and '{' in data:
|
||
data = json.loads(data)
|
||
base_url, params = parse_url(url)
|
||
city_row = None
|
||
if CITY_ID not in (None, '') and LAT not in (None, '') and LNG not in (None, ''):
|
||
city_row = {'city_id': str(CITY_ID), 'lat': str(LAT), 'lng': str(LNG)}
|
||
print('详情包 id:', HD_ID, 'poi:', POI_ID, 'proxy:', PROXY)
|
||
code, body = run_shelf_request(
|
||
base_url, params, headers, data, suggest_propagate, POI_ID,
|
||
CHECK_IN_DATE, CHECK_OUT_DATE, PROXY, city_row,
|
||
)
|
||
print('结束 code=%s' % code)
|
||
if isinstance(body, dict) and body.get('code') == 0:
|
||
print('shelf 成功 code=0') |