upload hotel shelf and area search

This commit is contained in:
mjz
2026-12-05 17:56:43 +08:00
commit 0640568feb
19 changed files with 5171 additions and 0 deletions
+184
View File
@@ -0,0 +1,184 @@
import re
import pymysql
class All_Setting():
def __init__(self,host,port,db):
self.host = host
self.port = port
self.db = db
def remove_symbols(self,text):
pattern = re.compile(r'[^\w\s]')
return pattern.sub('', text)
def get_chinese(self,text,printTxt=False):
# text = "海王星辰(广州智慧城店)"
pattern = r'[^\w\s]'
result = re.sub(pattern, '', text)
if printTxt:
print(result)
return result
def get_shoppingmalls(self,sql):
res_list = []
conn = pymysql.connect(
host= self.host, # 我的IP地址
port=self.port, # 不是字符串不需要加引号。
user='root',
password='Aliyun@7646!',
db=self.db,
charset='utf8mb4'
)
if conn:
print('ok')
cursor = conn.cursor()
res = cursor.execute(sql)
c2 = cursor.fetchall()
return c2
def write_data(self,sql,data):
conn = pymysql.connect(
host= self.host, # 我的IP地址
port=self.port, # 不是字符串不需要加引号。
user='root',
password='Aliyun@7646!',
db=self.db,
charset='utf8mb4'
)
# 拿到游标
if conn:
print("连接成功!")
cursor = conn.cursor()
cursor.executemany(sql,data)
conn.commit()
cursor.close()
conn.close() # 添加连接关闭
def update_data(self,sql):
conn = pymysql.connect(
host= self.host, # 我的IP地址
port=self.port, # 不是字符串不需要加引号。
user='root',
password='Aliyun@7646!',
db=self.db,
charset='utf8mb4'
)
# 拿到游标
if conn:
print("连接成功!")
cursor = conn.cursor()
cursor.execute(sql)
conn.commit()
cursor.close()
conn.close() # 添加连接关闭
def update_data_many(self,sql, values):
conn = pymysql.connect(
host= self.host, # 我的IP地址
port=self.port, # 不是字符串不需要加引号。
user='root',
password='Aliyun@7646!',
db=self.db,
charset='utf8mb4'
)
# 拿到游标
if conn:
print("连接成功!")
cursor = conn.cursor()
cursor.executemany(sql, values)
conn.commit()
cursor.close()
conn.close() # 添加连接关闭
def write_data_one(self,sql,data):
conn = pymysql.connect(
host= self.host, # 我的IP地址
port=self.port, # 不是字符串不需要加引号。
user='root',
password='Aliyun@7646!',
db=self.db,
charset='utf8mb4'
)
# 拿到游标
if conn:
print("连接成功!")
cursor = conn.cursor()
cursor.execute(sql,data)
conn.commit()
cursor.close()
conn.close() # 添加连接关闭
def get(self,sql):
conn = pymysql.connect(
host= self.host, # 我的IP地址
port=self.port, # 不是字符串不需要加引号。
user='root',
password='Aliyun@7646!',
db=self.db,
charset='utf8mb4'
)
# 拿到游标
if conn:
print("连接成功!")
cursor = conn.cursor()
cursor.execute(sql)
result = cursor.fetchall()
cursor.close()
conn.close() # 添加连接关闭
return result
import json
import time,requests
def get_sign_meituan(url, dfpid, data):
url_mtg = "http://118.89.119.254:18003/mt_jym_1_2"
payload = json.dumps({
"url": url,
"data": data,
"dfpid": dfpid,
"method": "POST",
"ua_type": "android"
})
headers = {
'token': 'j760kynsopjfm0sa9ghjwsd',
'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
'Content-Type': 'application/json'
}
response1 = requests.request("POST", url_mtg, headers=headers, data=payload)
print(response1.text)
mtgsig1 = response1.json()
return str(mtgsig1)
def get_sign_waimai(url, dfpid, data):
print('我是外卖mtg')
url_mtg = "http://118.89.119.254:18003/get_mt_tg_0507_jym"
payload = json.dumps({
"url": url,
"data": data,
"dfpid": dfpid,
"method": "POST",
# "ua_type": "android"
})
headers = {
'token': 'j760kynsopjfm0sa9ghjwsd',
'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
'Content-Type': 'application/json'
}
response = requests.request("POST", url_mtg, headers=headers, data=payload)
mtgsig = response.json()
print(mtgsig)
return str(mtgsig)
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
@@ -0,0 +1,591 @@
# shelf 组包+发送,逻辑从 酒店详情.py run_shelf 复制;不含领任务、suggest、入库
import copy
import json
import os
import random
import sys
import time
from datetime import datetime, timedelta
from urllib.parse import parse_qs, quote, urlencode, urlparse
from curl_cffi import requests
import newsetting as ten
# ============ 配置区:改这里 ============
HD_ID = 20584 # hotel_hd 详情包 id
AREA_NAME = '天河客运站' # hotel_area_search 里这次搜索的区域
POI_ID = '193415547' # 酒店 poiId
CHECK_IN_DATE = (datetime.now() + timedelta(days=1)).strftime('%Y-%m-%d') # 入住,明天
CHECK_OUT_DATE = (datetime.now() + timedelta(days=2)).strftime('%Y-%m-%d') # 离店,后天
CHECK_IN_DATE = (datetime.now()).strftime('%Y-%m-%d') # 入住,今天
CHECK_OUT_DATE = (datetime.now() + timedelta(days=1)).strftime('%Y-%m-%d') # 入住,明天
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://qqol:qqol@122.246.5.147:21552", "https": "http://qqol:qqol@122.246.5.147:21552"}
PACKET_REQ_NUM = 20 # 这个详情包累计最多成功次数,以 hotel_hd.current_count 为准
USER = 'thzn-datagram0001' # 交任务账号
PWD = 'thzn-datagram0001' # 交任务密码
VENDOR = 'mt-datagram' # 项目标识
# ============ 配置区结束 ============
tent = ten.All_Setting(host='192.168.5.5', port=3306, db='mt_hotel')
tent2 = ten.All_Setting(host='192.168.5.5', port=3306, db='mt_hotel') # hotel_hd 已迁到 mt_hotel
sys.path.insert(0, r'C:\Users\mjz\Desktop\python\mjz\6_酒店')
sys.path.insert(0, r'C:\Users\mjz\Desktop\python\mjz\小程序逆向\AI代码')
from 小程序mtgsig import get_mtgsig
from 酒店任务拿交 import upload_task_datagram, cancel_task, latest_cities
import 区域搜索列表
# 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} and current_count<20
'''
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 update_hd(hd_id, code, area_name):
# 成功累计请求数;418/403/401 写 is_ok。关键词整段重写,最多 3 个
rows = list(tent2.get_shoppingmalls('SELECT keywords FROM hotel_hd WHERE id=%s' % hd_id))
if not rows:
print('hotel_hd 没有这个 id 的包:', hd_id)
return
names = []
if rows[0][0]:
for name in str(rows[0][0]).split(','):
if name and name not in names:
names.append(name)
if area_name not in names:
if len(names) >= 3:
print('关键词已有3个,不新增', hd_id, names, area_name)
else:
names.append(area_name)
keyword_text = ','.join(names).replace("'", "''")
if code == 200:
sql = f'''
UPDATE hotel_hd SET current_count=IFNULL(current_count,0)+1,req_count=IFNULL(req_count,0)+1,keywords='{keyword_text}' WHERE id={hd_id}
'''
elif code in (418, 403, 401):
sql = f'''
UPDATE hotel_hd SET is_ok={code},req_count=IFNULL(req_count,0)+1,keywords='{keyword_text}' WHERE id={hd_id}
'''
else:
sql = f'''
UPDATE hotel_hd SET req_count=IFNULL(req_count,0)+1,keywords='{keyword_text}' WHERE id={hd_id}
'''
tent2.update_data(sql)
print('回写', hd_id, code, keyword_text)
def find_shelf_packet(area_name):
# 已跑过这个关键词、成功次数还没到 20 的包排前面,其余随机。一次取出,本地找 shelf
keyword = str(area_name).replace("'", "''")
rows = list(tent2.get_shoppingmalls('''
SELECT id, json_data, keywords FROM hotel_hd
WHERE title LIKE '%%美团酒店详情%%' AND is_ok IS NULL AND IFNULL(current_count,0)<20
ORDER BY FIND_IN_SET('%s', IFNULL(keywords,''))>0 DESC, RAND()
LIMIT 30
''' % keyword))
for row in rows:
url, headers, data = json.loads(row[1])
if '/hotel/core/router/shelf' not in url:
continue
if isinstance(data, str) and '{' in data:
data = json.loads(data)
names = []
if row[2]:
for name in str(row[2]).split(','):
if name and name not in names:
names.append(name)
if area_name in names:
print('用详情包', row[0], '已跑过', area_name)
else:
print('用详情包', row[0])
return row[0], url, headers, data
print('没有可用 shelf 包')
return None, None, None, None
def run_shelf_hotel(area_name, poi_id, hotel_name, pd, check_in, check_out, city='广州'):
# 传入关键词、poi、店名、整份 propagate、入住、离店、城市。找一个 shelf 包打一发,再回写 hotel_hd
hd_id, url, headers, data = find_shelf_packet(area_name)
if not url:
return
base_url, params = parse_url(url)
city_row = 区域搜索列表.get_city_row(city)
if not city_row:
return
proxies = 区域搜索列表.get_proxies(city)
if proxies:
proxy = json.loads(proxies[random.randint(0, len(proxies) - 1)][0])
else:
proxy = PROXY
print('shelf', hd_id, area_name, poi_id, hotel_name, check_in, check_out, city)
code, body = run_shelf_request(
base_url, params, headers, data, pd, str(poi_id),
check_in, check_out, proxy, city_row,
)
update_hd(hd_id, code, area_name)
print('结束 code=%s' % code, hd_id, poi_id, hotel_name)
return code, body
def submit_task(clientid, task_data, data_json):
# 用领任务时的 clientId、整份任务、shelf 返回交任务。成功后 status 写成已提交
resp = upload_task_datagram(
VENDOR, task_data['uniqueId'], VENDOR,
task_data['selectedCity'], clientid, USER, PWD, data_json,
)
print('交完', clientid, resp)
if resp['code'] != 0:
print('交失败', clientid, resp['code'])
return resp
unique_id = str(task_data['uniqueId']).replace("'", "''")
tent.update_data('''
UPDATE hotel_task SET status='已提交' WHERE unique_id='%s'
''' % unique_id)
print('已提交', task_data['uniqueId'])
return resp
def save_hotel_json(body, task_data):
# shelf 成功后的报文写入 hotel_json,字段和酒店详情一致
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(body), task_data['hotelId'], task_data['cityId'], task_data['hotelName'],
task_data['cityName'], task_data['checkInDate'], task_data['checkOutDate']),))
print('酒店入库', task_data['hotelId'], task_data['hotelName'])
def run_chain(city):
# 没找到就再领下一条。搜到并打完 shelf、交完任务就停
while True:
result = 区域搜索列表.run_client(city)
if result == 'empty':
return 'empty'
if result == 'stop' or result is None:
print('停止')
return 'stop'
if result == 'next':
continue
if result[0] == 'cancel':
client_id = result[1]
task_data = result[2]
resp = cancel_task(
task_data['uniqueId'], 30, VENDOR,
task_data['selectedCity'], client_id, USER, PWD,
)
print('取消', client_id, task_data['uniqueId'], resp)
if resp['code'] != 0:
print('取消失败,停止', client_id, resp['code'])
return 'stop'
continue
area_name, client_id, poi_id, hotel_name, pd, check_in, check_out, unique_id, task_data = result
shelf = run_shelf_hotel(area_name, poi_id, hotel_name, pd, check_in, check_out, city)
if shelf is None:
print('没有 shelf 包,停止')
return 'stop'
code, body = shelf
if code != 200:
print('shelf 未成功,停止', code, poi_id, hotel_name)
return 'stop'
submit_task(client_id, task_data, body)
save_hotel_json(body, task_data)
return 'done'
def run_cities():
# latest_cities 一次返回当前有任务的城市。按顺序用第一个还在里面的。做完一条再从广州看
cities = ['广州', '深圳', '北京', '上海', '杭州', '成都', '苏州', '南京', '青岛']
while True:
rows = latest_cities(VENDOR, USER, PWD)
city = None
for name in cities:
short = str(name).replace('市', '')
selected_city = None
for selected in rows:
if short in selected['selectedCity']:
selected_city = selected['selectedCity']
break
if selected_city:
print('任务城市', selected_city)
city = name
break
print(name, '没任务')
if not city:
print('这些城市都没任务')
return
print('跑', city)
result = run_chain(city)
if result == 'done' or result == 'empty':
continue
return
def load_area_hotels(area_name):
# 广州东站搜索结果,pd 是整份 propagateData
sql = f'''
SELECT poi_id, poi_name, pd
FROM hotel_area_search
WHERE area_name='{area_name}'
'''
rows = tent.get_shoppingmalls(sql)
hotels = []
for row in rows:
hotels.append({
'poi_id': str(row[0]),
'poi_name': row[1],
'pd': json.loads(row[2]),
})
print(area_name, '酒店', len(hotels), '入住', CHECK_IN_DATE, '离店', CHECK_OUT_DATE)
return hotels
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'] = poi_id
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'] = start
business['end'] = end
business['hourRoomStart'] = start
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')
# 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__':
for i in range(100):
run_cities()
# aa = [
# # 20788,
# # 20784,
# # 19817,
# # 20776,
# # 20773,
# # 20659,
# # 21273,
# # 20623,
# # 20620,
# # 20632,
# # 20638,
# # 20641,
# # 20644,
# # 20647,
# # 20602,
# # 20605,
# # 20599,
# # 20593,
# # 20587,
# # 20584,
# # 20693,
# # 20688,
# 20960,
# # 20678,
# ]
# # 广州东站 9 家 + 天河北/广州东站 13 家,共 22 条。两边都有的酒店各请求一次
# keyword_hotels = {
# "同德围": ["1012062896156277", "1256250978", "1529413963", "1548521880", "1691338433", "1965680891", "5616327", "625983", "625985", "758670205"]
# }
# for i in range(len(aa)):
# url, headers, data = get_hd_packet(aa[i])
# 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)}
# count_rows = list(tent2.get_shoppingmalls('SELECT current_count FROM hotel_hd WHERE id=%s' % aa[i]))
# current_count = count_rows[0][0]
# if current_count is None:
# current_count = 0
# if current_count >= PACKET_REQ_NUM:
# print('这个包 current_count 已有%s,停止' % current_count, aa[i])
# continue
# stop_packet = False # 401/418/403 或 current_count 满 20 后停掉这个包
# for area_name, poi_ids in keyword_hotels.items():
# all_hotels = load_area_hotels(area_name)
# by_id = {}
# for hotel in all_hotels:
# by_id[hotel['poi_id']] = hotel
# hotels = []
# for poi_id in poi_ids:
# hotels.append(by_id[poi_id])
# print('详情包 id:', aa[i], '关键词:', area_name, '酒店数:', len(hotels), 'proxy:', PROXY)
# for hotel in hotels:
# if current_count >= PACKET_REQ_NUM:
# print('这个包 current_count 已有%s,停止' % current_count, aa[i])
# stop_packet = True
# break
# print('第%s次' % (current_count + 1), hotel['poi_id'], hotel['poi_name'])
# code, body = run_shelf_request(
# base_url, params, headers, data, hotel['pd'], hotel['poi_id'],
# CHECK_IN_DATE, CHECK_OUT_DATE, PROXY, city_row,
# )
# update_hd(aa[i], code, area_name)
# if code == 200:
# insert_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(insert_sql, ((
# json.dumps(body, ensure_ascii=False),
# hotel['poi_id'],
# CITY_ID,
# hotel['poi_name'],
# None,
# CHECK_IN_DATE,
# CHECK_OUT_DATE,
# ),))
# print('已入库', hotel['poi_id'], hotel['poi_name'])
# current_count += 1
# print('结束 code=%s current_count=%s, 用的HD_ID是%s, 搜索关键词是%s' % (code, current_count, aa[i], area_name))
# if code in (401, 418, 403):
# print('错误响应,停止这个包', aa[i], code)
# stop_packet = True
# break
# if current_count >= PACKET_REQ_NUM:
# print('这个包 current_count 已有%s,停止' % current_count, aa[i])
# stop_packet = True
# break
# if stop_packet:
# break
# print('这个包 current_count=%s' % current_count, aa[i])
+184
View File
@@ -0,0 +1,184 @@
import re
import pymysql
class All_Setting():
def __init__(self,host,port,db):
self.host = host
self.port = port
self.db = db
def remove_symbols(self,text):
pattern = re.compile(r'[^\w\s]')
return pattern.sub('', text)
def get_chinese(self,text,printTxt=False):
# text = "海王星辰(广州智慧城店)"
pattern = r'[^\w\s]'
result = re.sub(pattern, '', text)
if printTxt:
print(result)
return result
def get_shoppingmalls(self,sql):
res_list = []
conn = pymysql.connect(
host= self.host, # 我的IP地址
port=self.port, # 不是字符串不需要加引号。
user='root',
password='Aliyun@7646!',
db=self.db,
charset='utf8mb4'
)
if conn:
print('ok')
cursor = conn.cursor()
res = cursor.execute(sql)
c2 = cursor.fetchall()
return c2
def write_data(self,sql,data):
conn = pymysql.connect(
host= self.host, # 我的IP地址
port=self.port, # 不是字符串不需要加引号。
user='root',
password='Aliyun@7646!',
db=self.db,
charset='utf8mb4'
)
# 拿到游标
if conn:
print("连接成功!")
cursor = conn.cursor()
cursor.executemany(sql,data)
conn.commit()
cursor.close()
conn.close() # 添加连接关闭
def update_data(self,sql):
conn = pymysql.connect(
host= self.host, # 我的IP地址
port=self.port, # 不是字符串不需要加引号。
user='root',
password='Aliyun@7646!',
db=self.db,
charset='utf8mb4'
)
# 拿到游标
if conn:
print("连接成功!")
cursor = conn.cursor()
cursor.execute(sql)
conn.commit()
cursor.close()
conn.close() # 添加连接关闭
def update_data_many(self,sql, values):
conn = pymysql.connect(
host= self.host, # 我的IP地址
port=self.port, # 不是字符串不需要加引号。
user='root',
password='Aliyun@7646!',
db=self.db,
charset='utf8mb4'
)
# 拿到游标
if conn:
print("连接成功!")
cursor = conn.cursor()
cursor.executemany(sql, values)
conn.commit()
cursor.close()
conn.close() # 添加连接关闭
def write_data_one(self,sql,data):
conn = pymysql.connect(
host= self.host, # 我的IP地址
port=self.port, # 不是字符串不需要加引号。
user='root',
password='Aliyun@7646!',
db=self.db,
charset='utf8mb4'
)
# 拿到游标
if conn:
print("连接成功!")
cursor = conn.cursor()
cursor.execute(sql,data)
conn.commit()
cursor.close()
conn.close() # 添加连接关闭
def get(self,sql):
conn = pymysql.connect(
host= self.host, # 我的IP地址
port=self.port, # 不是字符串不需要加引号。
user='root',
password='Aliyun@7646!',
db=self.db,
charset='utf8mb4'
)
# 拿到游标
if conn:
print("连接成功!")
cursor = conn.cursor()
cursor.execute(sql)
result = cursor.fetchall()
cursor.close()
conn.close() # 添加连接关闭
return result
import json
import time,requests
def get_sign_meituan(url, dfpid, data):
url_mtg = "http://118.89.119.254:18003/mt_jym_1_2"
payload = json.dumps({
"url": url,
"data": data,
"dfpid": dfpid,
"method": "POST",
"ua_type": "android"
})
headers = {
'token': 'j760kynsopjfm0sa9ghjwsd',
'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
'Content-Type': 'application/json'
}
response1 = requests.request("POST", url_mtg, headers=headers, data=payload)
print(response1.text)
mtgsig1 = response1.json()
return str(mtgsig1)
def get_sign_waimai(url, dfpid, data):
print('我是外卖mtg')
url_mtg = "http://118.89.119.254:18003/get_mt_tg_0507_jym"
payload = json.dumps({
"url": url,
"data": data,
"dfpid": dfpid,
"method": "POST",
# "ua_type": "android"
})
headers = {
'token': 'j760kynsopjfm0sa9ghjwsd',
'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
'Content-Type': 'application/json'
}
response = requests.request("POST", url_mtg, headers=headers, data=payload)
mtgsig = response.json()
print(mtgsig)
return str(mtgsig)
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
+943
View File
@@ -0,0 +1,943 @@
import json
import random
import time
import requests as task_requests
from curl_cffi import requests
import sys
sys.path.insert(0, r'C:\Users\mjz\Desktop\python\mjz\6_酒店')
sys.path.insert(0, r'C:\Users\mjz\Desktop\python\mjz\小程序逆向\AI代码')
import 酒店详情
from 小程序mtgsig import get_mtgsig
from 酒店任务拿交 import get_task, latest_cities
tent = 酒店详情.tent # mt_hotel,hotel_suggest_hd 也在这
tent2 = 酒店详情.tent2 # project_proxy 城市和代理
PAGE_LIMIT = 10 # 每页条数。返回里没有 hotelCells 才算这个区域翻完
PAGE_SKIP = 10 # 同一关键词、同一星级筛选翻满这么多页还没有这家就跳过
# 列表底稿 hotelStar=2,3 对应高档/四星、豪华/五星。分号后的 0,1 沿用底稿。按文字包含匹配
STAR_WORDS = (
('高档', '2;0,1', '["3_高档/四星"]'),
('豪华', '3;0,1', '["3_豪华/五星"]'),
('四星', '2;0,1', '["3_高档/四星"]'),
('五星', '3;0,1', '["3_豪华/五星"]'),
)
CITY_NAME = '广州市' # hotel_area_keyword 城市
PROXY_CITY = '广州' # proxs_list.city
USER = 'thzn-datagram0001' # 任务接口账号
PWD = 'thzn-datagram0001' # 任务接口密码
VENDOR = 'mt-datagram' # 项目标识
CITY = '广东省:20_广州市' # 只领广州
CLIENT_PREFIX = 'area' # 每次领任务换一个 clientId
STOP_CODES = (305, 306, 310, 318, 320, 337, 338) # 没任务或超额就停
LIST_URL = 'https://ihotel.meituan.com/core/searchapi/hotel/list'
# 列表请求底。账号/坐标/日期/关键词运行时盖,不读抓包文件
LIST_PARAMS = {
'yodaReady': 'wx',
'csecappid': 'wxde8ac0a21135c07d',
'csecplatform': '3',
'csecversionname': '10.47.1',
'csecversion': '4.0.0',
'openId': 'oJVP50D-b_jEnTe80yI0J-cvDSFo',
'antiRepPlatform': 'Android',
'programName': 'mt',
'utm_medium': 'WEIXINPROGRAM',
'openIdCipher': 'AwQAAABJAgAAAAEAAAAyAAAAPLgC95WH3MyqngAoyM/hf1hEoKrGdo0pJ5DI44e1wGF9AT3PH7Wes03actC2n/GVnwfURonD78PewMUppAAAADhx9XRiZddltpeR0DrfC6yJIRpSOzQItDfTSk9o5Tfv9s1bXt+UodWLMoM02+hrhwsLwT7EfzPz8A==',
'utm_campaign': 'entry%3DMTLive_scene%3D1089',
'token': 'AgFFJp1-0oN-_Al7zGNkFMgCHyrAUJXVoa9Jh_e4P1i1_9bGfYjYlbERWcy0rwFFmuK-4PJ-WqE4rgAAAADaPgAA-2dXGpIIYh-mIEDXUfSJQj3hOlA5e9vT6LHe83By_r9yyKiu6YOmGkVHhP6cLmja',
'usertoken': 'AgFFJp1-0oN-_Al7zGNkFMgCHyrAUJXVoa9Jh_e4P1i1_9bGfYjYlbERWcy0rwFFmuK-4PJ-WqE4rgAAAADaPgAA-2dXGpIIYh-mIEDXUfSJQj3hOlA5e9vT6LHe83By_r9yyKiu6YOmGkVHhP6cLmja',
'userToken': 'AgFFJp1-0oN-_Al7zGNkFMgCHyrAUJXVoa9Jh_e4P1i1_9bGfYjYlbERWcy0rwFFmuK-4PJ-WqE4rgAAAADaPgAA-2dXGpIIYh-mIEDXUfSJQj3hOlA5e9vT6LHe83By_r9yyKiu6YOmGkVHhP6cLmja',
'userId': '9468263097',
'userid': '9468263097',
'uuid': '1a22c23c8e112-a67fd1c5694b60-0-0-1a22c23c8e2c8',
'locateCityId': '20',
'locatecityid': '20',
'appMiniVersion': '10.47.100',
'lat': '23.122513',
'lng': '113.285982',
'sort': 'smart',
'newLandmarkId': '1634700387',
'hotelStar': '2,3;0,1',
'areaName': '广州塔',
'disablePersonalizedAdvertising': 'false',
'disablePersonalizedSearch': 'false',
'attr_28': '129',
'wifiList': '%5B%5D',
'q': '广州塔',
'sourceType': 'hotelSearch',
'limit': '10',
'offset': '0',
'remoteJumpEnabled': 'true',
'queryRewrite': 'rewrite',
'remoteCenter': '',
'category': '5',
'accommodationType': '1',
'newcate': '1',
'flagshipFilter': '1',
'ste': '',
'searchKeywordSource': '',
'inputKeyword': '',
'propagateData': '',
'hotel_queryid': '1a22c23c8e112-a67fd1c5694b60-0-0-1a22c23c8e2c81796120092540',
'tipBoothId': '94001296',
'userLocationType': '0',
'citySwitch': '1',
'designRevisionType': '1',
'riskLevel': '71',
'optimusCode': '10',
'hotelTypeFilter': '1',
'hotelCustomGpsStatus': '0',
'pageRealTime': '0',
'cellTagType': '1',
'fingerprint': '',
'abStrategy': '{}',
'wtt_region_id': '',
'wtt_region_version': '',
'wtt_region_type': 'nib',
'magicMemberCode': '1105,1106',
'simplifyField': 'false',
'templateIdVersion': '1:v2',
'mid': '',
'landmarkPosition': '',
'pluginCardShowMap': '{}',
'bannerSort': '0',
'selectedFilterItemsReport': '["3_高档/四星","3_豪华/五星"]',
'page_source': 'hotel_home',
'appletAppId': 'wxde8ac0a21135c07d',
'componentActiveStatus': '0',
'client': 'android',
'startDay': '20261201',
'endDay': '20261201',
'cityId': '20',
'ci': '20',
'gps_cityid': '20',
'latlng': '23.122513,113.285982',
'cate': '20',
'cateId': '20',
'version_name': '9.14.800',
'platform_business': 'meituan',
'appletVersionName': '10.47.1',
'riskPlatform': '13',
'mypos': '23.122513,113.285982',
'channelSelectCityId': '20',
'clientRequestTime': '1796120092549',
'crossPlatform': '1',
'utm_fp': 'MINI_PROGRAM',
'wechatVersion': '8.0.77',
'SDKVersion': '3.17.6',
}
# 从 suggest 包盖到列表上的账号字段。列表里没有的键不动
IDENTITY_KEYS = [
'token', 'usertoken', 'userToken', 'userId', 'userid', 'uuid',
'openId', 'openIdCipher', 'utm_campaign', 'lat', 'lng',
'SDKVersion', 'appMiniVersion', 'appletVersionName', 'csecversionname', 'wechatVersion',
'locateCityId', 'locatecityid',
]
def sql_str(value):
return str(value).replace("'", "''")
def create_tables():
tent.update_data('''
CREATE TABLE IF NOT EXISTS hotel_area_keyword (
id int NOT NULL AUTO_INCREMENT,
area_name varchar(100) NOT NULL,
city_name varchar(50) NOT NULL,
check_in_date date NOT NULL,
check_out_date date NOT NULL,
page_count int NOT NULL DEFAULT 0,
hotel_count int NOT NULL DEFAULT 0,
is_ok int NULL,
created_at datetime DEFAULT CURRENT_TIMESTAMP,
updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE KEY uk_area_date (area_name, check_in_date, check_out_date)
)
''')
tent.update_data('''
CREATE TABLE IF NOT EXISTS hotel_area_search (
id int NOT NULL AUTO_INCREMENT,
parent_id int NOT NULL,
area_name varchar(100) NOT NULL,
poi_id varchar(32) NOT NULL,
poi_name varchar(200) NOT NULL,
pd mediumtext NOT NULL,
page_offset int NOT NULL,
check_in_date date NOT NULL,
check_out_date date NOT NULL,
suggest_id int NULL,
star_filter varchar(200) NULL,
created_at datetime DEFAULT CURRENT_TIMESTAMP,
updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE KEY uk_area_poi_date_star (area_name, poi_id, check_in_date, check_out_date, star_filter),
KEY idx_parent_id (parent_id)
)
''')
print('表已就绪 hotel_area_keyword / hotel_area_search')
rewrite_pd()
ensure_star_filter()
def rewrite_pd():
# 旧表把 pd 拆成了 content_transparent 等列。合成整份后再删掉拆列
cols = tent.get_shoppingmalls('SHOW COLUMNS FROM hotel_area_search')
names = set(row[0] for row in cols)
if 'pd' not in names:
tent.update_data('ALTER TABLE hotel_area_search ADD COLUMN pd mediumtext NULL')
if 'content' not in names:
print('hotel_area_search 已是 pd 列')
return
rows = tent.get_shoppingmalls('''
SELECT id, content, content_transparent, poi_type, mystery_box_cross_activity_id
FROM hotel_area_search
''')
update_sql = 'UPDATE hotel_area_search SET pd=%s WHERE id=%s'
update_data = []
for row in rows:
pd_text = json.dumps({
'content': row[1],
'contentTransparent': row[2],
'poiType': row[3],
'mysteryBoxCrossActivityId': row[4],
}, ensure_ascii=False, separators=(',', ':'))
update_data.append((pd_text, row[0]))
if update_data:
tent.update_data_many(update_sql, update_data)
tent.update_data('''
ALTER TABLE hotel_area_search
DROP COLUMN content,
DROP COLUMN content_transparent,
DROP COLUMN poi_type,
DROP COLUMN mystery_box_cross_activity_id
''')
print('已把', len(update_data), '行改成 pd')
def ensure_star_filter():
cols = tent.get_shoppingmalls('SHOW COLUMNS FROM hotel_area_search')
names = set(row[0] for row in cols)
if 'star_filter' not in names:
tent.update_data('ALTER TABLE hotel_area_search ADD COLUMN star_filter varchar(200) NULL')
print('hotel_area_search 已加 star_filter')
indexes = tent.get_shoppingmalls('SHOW INDEX FROM hotel_area_search')
key_cols = {}
for row in indexes:
if row[2] not in key_cols:
key_cols[row[2]] = []
key_cols[row[2]].append(row[4])
if 'uk_area_poi_date_star' in key_cols:
return
if 'uk_area_poi_date' in key_cols:
tent.update_data('ALTER TABLE hotel_area_search DROP INDEX uk_area_poi_date')
tent.update_data('''
ALTER TABLE hotel_area_search
ADD UNIQUE KEY uk_area_poi_date_star (area_name, poi_id, check_in_date, check_out_date, star_filter)
''')
print('hotel_area_search 唯一键已带 star_filter')
def get_keywords():
rows = tent.get_shoppingmalls('''
SELECT area_name, COUNT(*) cnt FROM hotel_task
WHERE city_name='%s' AND area_name IS NOT NULL AND area_name<>''
GROUP BY area_name
ORDER BY cnt DESC, area_name
''' % sql_str(CITY_NAME))
done_rows = tent.get_shoppingmalls('''
SELECT DISTINCT area_name FROM hotel_area_keyword
WHERE city_name='%s' AND is_ok=1
''' % sql_str(CITY_NAME))
done = set(row[0] for row in done_rows)
keywords = []
for row in rows:
if row[0] in done:
continue
print('待搜', row[0], row[1])
keywords.append(row[0])
return keywords
def get_packets():
rows = tent.get_shoppingmalls('''
SELECT id, json_data FROM hotel_suggest_hd
WHERE title='酒店搜索推荐' AND is_ok IS NULL
''')
packets = []
for row in rows:
url, headers, data = json.loads(row[1])
params = 酒店详情.parse_url(url)[1]
if 'lat' not in params or 'lng' not in params:
print('包没有坐标,跳过', row[0])
continue
packets.append({
'id': row[0],
'params': params,
'headers': headers,
'mtgsig': headers['mtgsig'],
})
random.shuffle(packets)
print('可用 suggest 包', len(packets))
return packets
def get_city_row(city_name):
# project_proxy.citylist,level=2。和酒店详情一样按城市名取 mt_city_id、坐标
name = str(city_name).replace('市', '')
rows = tent2.get_shoppingmalls('''
SELECT lat, lng, mt_city_id FROM project_proxy.citylist
WHERE level=2 AND name='%s'
LIMIT 1
''' % sql_str(name))
if not rows:
print('citylist 没有这个城市', city_name)
return None
return {'lat': str(rows[0][0]), 'lng': str(rows[0][1]), 'city_id': str(rows[0][2])}
def task_selected_city(city_name):
# 任务接口的 selectedCity。城市名包含即可,和酒店详情 get_one_task 一样
cities = latest_cities(VENDOR, USER, PWD)
name = str(city_name).replace('市', '')
for selected in cities:
if name in selected['selectedCity']:
print('任务城市', selected['selectedCity'])
return selected['selectedCity']
print('任务接口没有这个城市', city_name)
return None
def get_proxies(city_name=None):
if not city_name:
city_name = PROXY_CITY
rows = tent2.get_shoppingmalls('''
SELECT prox_data, city FROM project_proxy.proxs_list
WHERE channel AND city='%s'
''' % sql_str(city_name))
print(city_name, '代理', len(rows))
return list(rows)
name = str(city_name).replace('市', '')
rows = tent2.get_shoppingmalls('''
SELECT prox_data, city FROM project_proxy.proxs_list
WHERE channel AND city IS NOT NULL AND city!=''
''')
matched = []
for row in rows:
if row[1] and (row[1] in name or name in row[1]):
matched.append(row)
print(name, '代理', len(matched))
return matched
def ensure_keyword(area_name, check_in, check_out, city_name=None):
if not city_name:
city_name = CITY_NAME
rows = tent.get_shoppingmalls('''
SELECT id, is_ok FROM hotel_area_keyword
WHERE area_name='%s' AND check_in_date='%s' AND check_out_date='%s'
''' % (sql_str(area_name), check_in, check_out))
if rows:
return rows[0][0]
tent.write_data('''
INSERT INTO hotel_area_keyword
(area_name, city_name, check_in_date, check_out_date, page_count, hotel_count, is_ok)
VALUES (%s,%s,%s,%s,0,0,NULL)
''', [(area_name, city_name, check_in, check_out)])
rows = tent.get_shoppingmalls('''
SELECT id FROM hotel_area_keyword
WHERE area_name='%s' AND check_in_date='%s' AND check_out_date='%s'
''' % (sql_str(area_name), check_in, check_out))
return rows[0][0]
def finish_keyword(keyword_id, page_count, is_ok):
count_rows = tent.get_shoppingmalls('''
SELECT COUNT(*) FROM hotel_area_search WHERE parent_id=%s
''' % keyword_id)
hotel_count = count_rows[0][0]
if is_ok is None:
is_ok_sql = 'NULL'
else:
is_ok_sql = str(is_ok)
tent.update_data('''
UPDATE hotel_area_keyword
SET page_count=%s, hotel_count=%s, is_ok=%s
WHERE id=%s
''' % (page_count, hotel_count, is_ok_sql, keyword_id))
print('关键词收尾 id=%s page_count=%s hotel_count=%s is_ok=%s' % (keyword_id, page_count, hotel_count, is_ok_sql))
def fill_params(suggest_params, area_name, offset, landmark_id, check_in, check_out, hotel_star_param, star_filter, city_row=None):
params = dict(LIST_PARAMS)
for key in IDENTITY_KEYS:
if key in params and key in suggest_params:
params[key] = suggest_params[key]
params['mypos'] = suggest_params['lat'] + ',' + suggest_params['lng']
params['latlng'] = suggest_params['lat'] + ',' + suggest_params['lng']
q = area_name
for i, ch in enumerate(area_name):
if not ch.isalnum():
q = area_name[:i]
break
params['q'] = q
params['areaName'] = q
params['limit'] = str(PAGE_LIMIT)
params['offset'] = str(offset)
params['startDay'] = check_in.replace('-', '')
params['endDay'] = check_out.replace('-', '')
params['hotelStar'] = hotel_star_param
params['selectedFilterItemsReport'] = star_filter
now_ms = str(int(time.time() * 1000))
params['clientRequestTime'] = now_ms
params['hotel_queryid'] = suggest_params['uuid'] + now_ms
if landmark_id:
params['newLandmarkId'] = landmark_id
else:
del params['newLandmarkId']
if city_row:
city_id = city_row['city_id']
params['cityId'] = city_id
params['ci'] = city_id
params['gps_cityid'] = city_id
params['channelSelectCityId'] = city_id
params['locateCityId'] = city_id
params['locatecityid'] = city_id
params['lat'] = city_row['lat']
params['lng'] = city_row['lng']
params['mypos'] = city_row['lat'] + ',' + city_row['lng']
params['latlng'] = params['mypos']
return params
def build_headers(suggest_headers):
headers = dict(suggest_headers)
酒店详情.set_m_traceid(headers)
return headers
def read_landmark_id(res):
data = res['data']
if 'keywordOption' not in data:
return None
option = data['keywordOption']
if not isinstance(option, dict):
return None
if 'selectKey' not in option or 'selectValue' not in option:
return None
if option['selectKey'] != 'newLandmarkId':
return None
if not option['selectValue']:
return None
return str(option['selectValue'])
def save_hotels(res, keyword_id, area_name, offset, suggest_id, seen, check_in, check_out, star_filter):
insert_sql = '''
INSERT INTO hotel_area_search
(parent_id, area_name, poi_id, poi_name, pd, page_offset, check_in_date, check_out_date, suggest_id, star_filter)
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
ON DUPLICATE KEY UPDATE
parent_id=VALUES(parent_id),
poi_name=VALUES(poi_name),
pd=VALUES(pd),
page_offset=VALUES(page_offset),
suggest_id=VALUES(suggest_id),
star_filter=VALUES(star_filter)
'''
insert_data = []
cells = res['data']['hotelCells']
for cell in cells:
ext = cell['extensionArea']['extension']
if 'propagateData' not in ext or 'poiId' not in ext:
continue
poi_id = str(ext['poiId'])
if poi_id in seen:
continue
seen.add(poi_id)
propagate = ext['propagateData']
poi_name = ''
for title_item in cell['titleArea']['title']:
if 'text' in title_item:
poi_name = title_item['text']['content']
break
if not poi_name:
print('没有店名', poi_id)
seen.remove(poi_id)
continue
insert_data.append((
keyword_id,
area_name,
poi_id,
poi_name,
json.dumps(propagate, ensure_ascii=False, separators=(',', ':')),
offset,
check_in,
check_out,
suggest_id,
star_filter,
))
if insert_data:
tent.write_data(insert_sql, insert_data)
print('本页入库', len(insert_data), 'offset', offset, '累计', len(seen))
return len(cells)
def mark_packet(suggest_id, is_ok):
tent.update_data('UPDATE hotel_suggest_hd SET is_ok=%s WHERE id=%s' % (is_ok, suggest_id))
print('suggest 包', suggest_id, 'is_ok', is_ok)
def add_packet_count(suggest_id):
tent.update_data('''
UPDATE hotel_suggest_hd
SET current_count=current_count+1, req_count=req_count+1
WHERE id=%s
''' % suggest_id)
print('suggest 请求数 +1', suggest_id)
def ensure_task_client_id():
# hotel_task 补这次领任务用的 client_id
cols = tent.get_shoppingmalls('SHOW COLUMNS FROM hotel_task')
names = set(row[0] for row in cols)
if 'client_id' in names:
return
tent.update_data('ALTER TABLE hotel_task ADD COLUMN client_id varchar(100) NULL')
print('hotel_task 已加 client_id')
def ensure_task_status():
# hotel_task 补搜索结果状态
cols = tent.get_shoppingmalls('SHOW COLUMNS FROM hotel_task')
names = set(row[0] for row in cols)
if 'status' in names:
return
tent.update_data("ALTER TABLE hotel_task ADD COLUMN status varchar(20) NULL")
print('hotel_task 已加 status')
def mark_task_missing(unique_id):
tent.update_data('''
UPDATE hotel_task SET status='没找到' WHERE unique_id='%s'
''' % sql_str(unique_id))
print('没找到', unique_id)
def save_task(data):
rows = tent.get_shoppingmalls('''
SELECT id FROM hotel_task WHERE unique_id='%s'
''' % sql_str(data['uniqueId']))
if rows:
print('任务已在库', rows[0][0], data['hotelId'], data['uniqueId'])
return
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 (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
'''
row = (
str(data['hotelId']),
str(data['cityId']),
data['hotelName'],
data['hotelAddress'],
data['cityName'],
data['checkInDate'],
data['checkOutDate'],
data['uniqueId'],
data['timeLeft'],
data['hotelStar'],
data['selectedCity'],
data['areaType'],
data['areaName'],
data['level'],
)
tent.write_data(sql, [row])
print('任务入库', data['hotelId'], data['hotelName'], data['uniqueId'])
def save_task_client(data, client_id):
# unique_id 已在库就只改 client_id,新任务插入时带上
rows = tent.get_shoppingmalls('''
SELECT id FROM hotel_task WHERE unique_id='%s'
''' % sql_str(data['uniqueId']))
if rows:
tent.update_data('''
UPDATE hotel_task SET client_id='%s' WHERE id=%s
''' % (sql_str(client_id), rows[0][0]))
print('重复任务,更新 client_id', rows[0][0], data['hotelId'], data['uniqueId'], client_id)
return
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, client_id
) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
'''
row = (
str(data['hotelId']),
str(data['cityId']),
data['hotelName'],
data['hotelAddress'],
data['cityName'],
data['checkInDate'],
data['checkOutDate'],
data['uniqueId'],
data['timeLeft'],
data['hotelStar'],
data['selectedCity'],
data['areaType'],
data['areaName'],
data['level'],
client_id,
)
tent.write_data(sql, [row])
print('任务入库', data['hotelId'], data['hotelName'], data['uniqueId'], client_id)
def request_page(params, packet, proxy):
url = 酒店详情.build_url(LIST_URL, params)
headers = build_headers(packet['headers'])
if 'openId' in headers:
open_id = headers['openId']
else:
open_id = headers['openid']
headers['mtgsig'] = get_mtgsig(url, '', packet['mtgsig'], open_id, 'GET')
response = requests.get(url, headers=headers, proxies=proxy, verify=False, http_version='v1', timeout=20)
return response
def packet_dead(response):
if response.status_code in (403, 418, 401):
return response.status_code
text = response.text
if '您的网络好像不太给力,请稍后再试' in text:
return 418
if 'Unauthorized' in text[:500]:
return 401
return None
def hotel_in_search(hotel_id, hotel_name):
rows = tent.get_shoppingmalls('''
SELECT poi_id, area_name, poi_name FROM hotel_area_search
WHERE poi_id='%s'
LIMIT 1
''' % sql_str(hotel_id))
if rows:
print('已在 hotel_area_search', rows[0][0], rows[0][1], rows[0][2])
return True
print('不在 hotel_area_search', hotel_id, hotel_name)
return False
def get_shelf_hotel(poi_id, area_name, check_in, check_out):
# shelf 用 poi、整份 propagate、入住离店,再加酒店名称
rows = tent.get_shoppingmalls('''
SELECT poi_id, poi_name, pd, check_in_date, check_out_date
FROM hotel_area_search
WHERE poi_id='%s' AND area_name='%s' AND check_in_date='%s' AND check_out_date='%s'
ORDER BY id DESC
LIMIT 1
''' % (sql_str(poi_id), sql_str(area_name), check_in, check_out))
if not rows:
rows = tent.get_shoppingmalls('''
SELECT poi_id, poi_name, pd, check_in_date, check_out_date
FROM hotel_area_search
WHERE poi_id='%s'
ORDER BY id DESC
LIMIT 1
''' % sql_str(poi_id))
if not rows:
print('hotel_area_search 没有这家', poi_id)
return None
return str(rows[0][0]), rows[0][1], json.loads(rows[0][2]), str(rows[0][3])[:10], str(rows[0][4])[:10]
def star_filter_of(hotel_star):
text = str(hotel_star)
for word, hotel_star_param, star_filter in STAR_WORDS:
if word in text:
return hotel_star_param, star_filter
return None
def latest_batch(area_name, star_filter, check_in, check_out):
rows = tent.get_shoppingmalls('''
SELECT id FROM hotel_area_keyword
WHERE area_name='%s' AND check_in_date='%s' AND check_out_date='%s'
ORDER BY id DESC
LIMIT 1
''' % (sql_str(area_name), check_in, check_out))
if not rows:
return None
keyword_id = rows[0][0]
page_rows = tent.get_shoppingmalls('''
SELECT MAX(page_offset) FROM hotel_area_search
WHERE parent_id=%s AND star_filter='%s'
AND check_in_date='%s' AND check_out_date='%s'
''' % (keyword_id, sql_str(star_filter), check_in, check_out))
max_offset = page_rows[0][0]
if max_offset is None:
start_page = 0
else:
start_page = int(max_offset) // PAGE_LIMIT + 1
print('最新一批', keyword_id, area_name, star_filter, '已翻', start_page, '页', check_in, check_out)
return keyword_id, start_page
def run_one_keyword(area_name, packet, proxies, state, target_poi_id, hotel_name, keyword_id, start_page, check_in, check_out, hotel_star_param, star_filter, city_row=None):
print('关键词', area_name, 'keyword_id', keyword_id, 'suggest', packet['id'], '日期', check_in, check_out, '目标', target_poi_id, hotel_name, '星级', star_filter, '从第', start_page + 1, '页')
proxy = json.loads(proxies[state['proxy_index']][0])
landmark_id = None
seen = set()
page_count = start_page
while True:
offset = page_count * PAGE_LIMIT
while True:
params = fill_params(packet['params'], area_name, offset, landmark_id, check_in, check_out, hotel_star_param, star_filter, city_row)
print('请求', params['q'], '区域', area_name, 'offset', offset, 'suggest', packet['id'], 'landmark', landmark_id)
try:
response = request_page(params, packet, proxy)
except requests.exceptions.RequestException as e:
print('代理连接失败', e)
state['proxy_index'] = (state['proxy_index'] + 1) % len(proxies)
proxy = json.loads(proxies[state['proxy_index']][0])
print('换广州 IP', state['proxy_index'])
continue
dead = packet_dead(response)
if dead:
print('包失效', response.status_code, response.text[:200])
mark_packet(packet['id'], dead)
finish_keyword(keyword_id, page_count, None)
return 'dead'
if response.status_code != 200:
print('HTTP 非200', response.status_code, response.text[:200])
finish_keyword(keyword_id, page_count, 0)
return 'next'
res = response.json()
if res['code'] != 200:
print('返回 code', res['code'], response.text[:200])
finish_keyword(keyword_id, page_count, 0)
return 'next'
add_packet_count(packet['id'])
data = res['data']
if not isinstance(data, dict):
print('没有data', response.text)
finish_keyword(keyword_id, page_count, None)
return 'stop'
if 'hotelCells' not in data:
print('没有hotelCells,翻完', area_name, list(data.keys()))
finish_keyword(keyword_id, page_count, 1)
print('搜完没有这家', target_poi_id, hotel_name, area_name)
return 'done'
save_hotels(res, keyword_id, area_name, offset, packet['id'], seen, check_in, check_out, star_filter)
page_count += 1
if landmark_id is None:
landmark_id = read_landmark_id(res)
print('newLandmarkId', landmark_id)
if target_poi_id in seen:
print('搜到酒店,区域还没翻完', target_poi_id, hotel_name, area_name)
finish_keyword(keyword_id, page_count, None)
return 'found'
if page_count >= PAGE_SKIP:
print('翻满10页没搜到', target_poi_id, hotel_name, area_name, star_filter)
finish_keyword(keyword_id, page_count, None)
return 'skip'
break
def run():
create_tables()
proxies = get_proxies()
if not proxies:
print('没有广州代理,停止')
return
packets = get_packets()
if not packets:
print('没有可用 suggest 包')
return
state = {'proxy_index': 0}
packet_i = 0
seq = 0
while packet_i < len(packets):
seq += 1
clientid = '%s%05d' % (CLIENT_PREFIX, seq)
try:
task = get_task(VENDOR, USER, PWD, clientid, CITY)
except task_requests.exceptions.RequestException as e:
print('领任务失败', clientid, e)
continue
if task['code'] != 0:
print('未领到', clientid, task['code'])
if task['code'] in STOP_CODES:
print('停止领任务', task['code'])
return
continue
data = task['data']
save_task(data)
hotel_id = str(data['hotelId'])
hotel_name = data['hotelName']
area_name = data['areaName']
hotel_star = data['hotelStar']
print('任务', clientid, hotel_id, hotel_name, area_name, hotel_star, data['checkInDate'], data['checkOutDate'])
if hotel_in_search(hotel_id, hotel_name):
continue
if not area_name:
print('任务没有区域', hotel_id, hotel_name)
continue
star = star_filter_of(hotel_star)
if star is None:
print('没有这个星级的筛选', hotel_id, hotel_name, hotel_star)
continue
hotel_star_param, star_filter = star
check_in = str(data['checkInDate'])[:10]
check_out = str(data['checkOutDate'])[:10]
batch = latest_batch(area_name, star_filter, check_in, check_out)
if batch is None:
keyword_id = ensure_keyword(area_name, check_in, check_out)
start_page = 0
else:
keyword_id, start_page = batch
if start_page >= PAGE_SKIP:
print('10页内没搜到,跳过', hotel_id, hotel_name, area_name, star_filter)
continue
searched = False
while packet_i < len(packets):
packet = packets[packet_i]
print('包', packet['id'], '搜', area_name, star_filter, hotel_id, hotel_name)
result = run_one_keyword(area_name, packet, proxies, state, hotel_id, hotel_name, keyword_id, start_page, check_in, check_out, hotel_star_param, star_filter)
if result == 'stop':
return
if result == 'dead':
packet_i += 1
again = latest_batch(area_name, star_filter, check_in, check_out)
if again is None:
start_page = 0
else:
keyword_id, start_page = again
if start_page >= PAGE_SKIP:
print('10页内没搜到,跳过', hotel_id, hotel_name, area_name, star_filter)
searched = True
break
continue
packet_i += 1
searched = True
break
if not searched:
print('包用完了,停')
return
def run_client(city='广州'):
# 随机一个 client_id,领一条这个城市的任务,搜索结果仍进 hotel_area_search
ensure_task_client_id()
ensure_task_status()
create_tables()
city_row = get_city_row(city)
if not city_row:
return 'stop'
selected_city = task_selected_city(city)
if not selected_city:
return 'empty'
proxies = get_proxies(city)
if not proxies:
print('没有代理,停止', city)
return 'stop'
packets = get_packets()
if not packets:
print('没有可用 suggest 包')
return 'stop'
client_id = '%s%s' % (city, random.randint(10000000, 99999999))
print('client_id', client_id)
try:
task = get_task(VENDOR, USER, PWD, client_id, selected_city)
except task_requests.exceptions.RequestException as e:
print('领任务失败', client_id, e)
return 'stop'
if task['code'] != 0:
print('未领到', client_id, task['code'])
if task['code'] == 318:
return 'empty'
if task['code'] in STOP_CODES:
return 'stop'
return 'next'
data = task['data']
unique_id = data['uniqueId']
save_task_client(data, client_id)
hotel_id = str(data['hotelId'])
hotel_name = data['hotelName']
area_name = data['areaName']
hotel_star = data['hotelStar']
check_in = str(data['checkInDate'])[:10]
check_out = str(data['checkOutDate'])[:10]
print('任务', client_id, hotel_id, hotel_name, area_name, hotel_star, check_in, check_out)
if hotel_in_search(hotel_id, hotel_name):
shelf_hotel = get_shelf_hotel(hotel_id, area_name, check_in, check_out)
if shelf_hotel is None:
return 'next'
poi_id, hotel_name, pd, shelf_check_in, shelf_check_out = shelf_hotel
print('返回', area_name, client_id, poi_id, hotel_name, check_in, check_out, unique_id)
return area_name, client_id, poi_id, hotel_name, pd, check_in, check_out, unique_id, data
if not area_name:
print('任务没有区域', hotel_id, hotel_name)
return 'next'
star = star_filter_of(hotel_star)
if star is None:
print('没有这个星级的筛选', hotel_id, hotel_name, hotel_star)
return 'next'
hotel_star_param, star_filter = star
batch = latest_batch(area_name, star_filter, check_in, check_out)
if batch is None:
keyword_id = ensure_keyword(area_name, check_in, check_out, city if str(city).endswith('市') else str(city) + '市')
start_page = 0
else:
keyword_id, start_page = batch
if start_page >= PAGE_SKIP:
print('10页内没搜到,跳过', hotel_id, hotel_name, area_name, star_filter)
mark_task_missing(unique_id)
return 'cancel', client_id, data
state = {'proxy_index': 0}
packet_i = 0
while packet_i < len(packets):
packet = packets[packet_i]
print('包', packet['id'], '搜', area_name, star_filter, hotel_id, hotel_name)
result = run_one_keyword(area_name, packet, proxies, state, hotel_id, hotel_name, keyword_id, start_page, check_in, check_out, hotel_star_param, star_filter, city_row)
if result == 'stop':
return 'stop'
if result == 'dead':
packet_i += 1
again = latest_batch(area_name, star_filter, check_in, check_out)
if again is None:
start_page = 0
else:
keyword_id, start_page = again
if start_page >= PAGE_SKIP:
print('10页内没搜到,跳过', hotel_id, hotel_name, area_name, star_filter)
mark_task_missing(unique_id)
return 'cancel', client_id, data
continue
if result == 'found':
shelf_hotel = get_shelf_hotel(hotel_id, area_name, check_in, check_out)
if shelf_hotel is None:
return 'next'
poi_id, hotel_name, pd, shelf_check_in, shelf_check_out = shelf_hotel
print('返回', area_name, client_id, poi_id, hotel_name, check_in, check_out, unique_id)
return area_name, client_id, poi_id, hotel_name, pd, check_in, check_out, unique_id, data
if result == 'skip':
mark_task_missing(unique_id)
return 'cancel', client_id, data
if result == 'done':
mark_task_missing(unique_id)
return 'next'
print('包用完了,停')
return 'stop'
if __name__ == '__main__':
aa = run_client()
print(aa)
+292
View File
@@ -0,0 +1,292 @@
# -*- coding: utf-8 -*-
import base64
import json
import os
import uuid
import requests
from datetime import date
from typing import Optional, Dict, Any, List
from colorama import init, Fore, Style
init(autoreset=True)
BASE_URL = "http://ktl-001.dsfdl-henan.xyz/openApi"
TIMEOUT = 15
# 任务接口直连,不走系统代理(本机 VPN):None 会被 requests 过滤掉,用空字符串才是真直连
DIRECT_PROXIES = {'http': '', 'https': ''}
LOG_DIR = "logs"
os.makedirs(LOG_DIR, exist_ok=True)
CODE_MSG = {
0: ("success", "请求成功"),
-1: ("server error", "服务本身错误"),
-2: ("Authorization failed", "账号密码错误或认证方式错误"),
305: ("现在没有任务了", "请稍后再试"),
306: ("您今日没有任务了", "明天再来吧"),
309: ("任务:开始", ""),
310: ("任务:已经结束", ""),
311: ("日期错误", "统计接口日期格式需严格 yyyy-MM-dd"),
312: ("网络通信出错", "上传/取消时可重试"),
313: ("任务还在处理中", "请勿重复提交"),
314: ("任务正在获取中", "请稍后重试"),
317: ("为了账号安全", "休息一会儿再做吧"),
318: ("当前城市没任务啦", "换个城市试试"),
319: ("服务维护中", "休息一会再做吧"),
324: ("提交和获取的任务不一致", "uniqueId 需保持一致"),
325: ("封号", ""),
326: ("上传文本格式有错", "需 JSON 格式"),
327: ("当前已领取任务", "请先完成再领新任务"),
328: ("重复取消任务", ""),
336: ("为了您的账号安全", "休息一下再来吧"),
337: ("正在做的任务数量超过限额", ""),
338: ("不在指定领取任务时间区间内", ""),
339: ("网络通信失败", "请重试"),
}
def _color_code(code: int) -> str:
if code == 0:
return f"{Fore.GREEN}{code}"
if code in CODE_MSG:
return f"{Fore.YELLOW}{code}"
return f"{Fore.RED}{code}"
def _log_response(api_name: str, resp: Dict[str, Any]):
code = resp.get("code", -1)
msg_en, msg_zh = CODE_MSG.get(code, (resp.get("message", ""), "未知错误"))
print(f"[{api_name}] 返回码: {_color_code(code)} {msg_en} | {msg_zh}")
def _auth(username: str, password: str) -> Dict[str, str]:
token = base64.b64encode(f"{username}:{password}".encode()).decode()
return {"Authorization": f"Basic {token}"}
def _get(url: str, username: str, password: str, params: Optional[dict] = None) -> Dict[str, Any]:
resp = requests.get(url, headers=_auth(username, password), params=params or {}, timeout=TIMEOUT, proxies=DIRECT_PROXIES)
resp.raise_for_status()
return resp.json()
def _post(url: str, username: str, password: str, params: Optional[dict] = None, json_data: Any = None) -> Dict[
str, Any]:
resp = requests.post(url, headers=_auth(username, password), params=params or {}, json=json_data, timeout=TIMEOUT, proxies=DIRECT_PROXIES)
resp.raise_for_status()
return resp.json()
def realtime_city_list(vendor_name: str,
username: str,
password: str,
checkin_date: Optional[str] = None,
checkout_date: Optional[str] = None) -> List[Dict[str, Any]]:
url = f"{BASE_URL}/realtimeCityList"
params = {"vendorName": vendor_name}
if checkin_date:
params["checkInDate"] = checkin_date
if checkout_date:
params["checkOutDate"] = checkout_date
resp = _get(url, username, password, params)
_log_response("realtime_city_list", resp)
return resp.get("data", [])
def realtime_checkinout_dates(vendor_name: str,
username: str,
password: str) -> List[Dict[str, str]]:
url = f"{BASE_URL}/realtimeCheckInOutDateList"
params = {"vendorName": vendor_name}
resp = _get(url, username, password, params)
_log_response("realtime_checkinout_dates", resp)
return resp.get("data", [])
def latest_cities(vendor_name: str, username: str, password: str) -> List[Dict[str, Any]]:
dates = realtime_checkinout_dates(vendor_name, username, password)
if not dates:
return []
latest = dates[0]
return realtime_city_list(vendor_name, username, password,
latest["checkInDate"], latest["checkOutDate"])
def get_task(vendor_name: str,
username: str,
password: str,
client_id: str,
selected_city: str,
checkin_date: Optional[str] = None,
checkout_date: Optional[str] = None) -> Dict[str, Any]:
url = f"{BASE_URL}/getTask"
params = {"vendorName": vendor_name, "clientId": client_id, "selectedCity": selected_city}
if checkin_date:
params["checkInDate"] = checkin_date
if checkout_date:
params["checkOutDate"] = checkout_date
resp = _get(url, username, password, params)
_log_response("get_task", resp)
return resp
# 交任务
def upload_task_datagram(original_vendor: str,
unique_id: str,
target_vendor: str,
selected_city: str,
client_id: str,
username: str,
password: str,
datagram_json: dict,
channel: Optional[str] = None) -> Dict[str, Any]:
url = f"{BASE_URL}/uploadTaskDatagram"
params = {"originalVendorName": original_vendor,
"targetVendorName": target_vendor,
"uniqueId": unique_id,
"selectedCity": selected_city,
"clientId": client_id}
if channel:
params["channel"] = channel
print(datagram_json)
print('==============')
print((params))
# 提交超时/连接失败重试,最多 3 次(含首次)
for i in range(30):
try:
resp = _post(url, username, password, params, json_data=datagram_json)
break
except (requests.exceptions.Timeout, requests.exceptions.ConnectionError) as e:
print(f"交任务失败,第{i + 1}次: {e}")
if i == 2:
raise
_log_response("upload_task_datagram", resp)
return resp
# 取消任务
def cancel_task(unique_id: str,
cancel_status: int,
vendor_name: str,
selected_city: str,
client_id: str,
username: str,
password: str) -> Dict[str, Any]:
url = f"{BASE_URL}/cancelTask"
params = {"uniqueId": unique_id,
"cancelStatus": cancel_status,
"vendorName": vendor_name,
"selectedCity": selected_city,
"clientId": client_id}
resp = _post(url, username, password, params)
_log_response("cancel_task", resp)
return resp
def get_one_task(VENDOR, USER, PWD, clientid, city_name):
cities = latest_cities(VENDOR, USER, PWD)
print(cities)
city = None
if city_name:
for selected in cities:
if city_name in selected['selectedCity']:
city = selected['selectedCity']
break
if not city:
return False
else:
city = cities[0]["selectedCity"]
print(f"实际获取任务城市: ",city)
# city = '上海市:10_上海市'
task = get_task(VENDOR, USER, PWD, clientid, city)
return task
def upload_one_task(VENDOR, USER, PWD, clientid, task_data, data_json):
upload_task_datagram(VENDOR, task_data.get('data').get('uniqueId'), VENDOR,
task_data.get('data').get('selectedCity'), clientid, USER, PWD,
data_json)
def cancel_one_task(VENDOR, USER, PWD, clientid, task_data, cancel_status):
return cancel_task(task_data.get('data').get('uniqueId'), cancel_status, VENDOR,
task_data.get('data').get('selectedCity'), clientid, USER, PWD)
if __name__ == '__main__':
'''
使用实例
'''
USER = "thzn-datagram0001"
PWD = "thzn-datagram0001"
VENDOR = "mt-datagram"
clientid = 'area85092537'
'''
VENDOR 可写死 项目标识
USER 可写死 账号
PWD 可写死 密码
clientid 单人可写死(多线程需修改) 客户端id
city 修改拿取城市的id 根据其他接口返回
'''
# 一、实时获取任务酒店入离日期列表
date_list = realtime_checkinout_dates(VENDOR, USER, PWD)
print(date_list)
# 取其中一组入离日期查询有任务的城市列表,不传日期默认取最近一组
# date_list[0] 即 {"checkInDate": "2023-05-15", "checkOutDate": "2023-05-16"}
# city_list = realtime_city_list(VENDOR, USER, PWD, date_list[0]['checkInDate'], date_list[0]['checkOutDate'])
# print(city_list)
# 任务获取
task = get_one_task(VENDOR, USER, PWD, clientid,'广州')
print(task)
'''
VENDOR 可写死 项目标识
USER 可写死 账号
PWD 可写死 密码
clientid 单人可写死(多线程需修改) 客户端id
city 修改拿取城市的id 根据其他接口返回
task_data为任务返回的数据json
task_data={
"code": 0,
"message": "success",
"data": {
"hotelId": "938833723",
"cityId": "50",
"hotelName": "杭州拱墅大运河轻居酒店",
"hotelAddress": "拱墅区湖州街555号顺网运河国际4号楼1层",
"cityName": "杭州市",
"checkInDate": "2025-12-01",
"checkOutDate": "2025-12-02",
"uniqueId": "20251130205014-32-32-3000001-443-411",
"timeLeft": 1046,
"hotelStar": "高档型",
"selectedCity": "浙江省:50_杭州市",
"areaType": "行政区/商圈",
"areaName": "汽车北站、国际会展中心",
"level": 0
}
}
data_json为采集获取到的json即上交数据
'''
# 任务提交
# task_data = json.loads(task)
# data_json = {}#返回原始报文即可
# upload_one_task(VENDOR, USER, PWD, clientid, task_data, data_json)
'''
任务取消示例
cancel_status 取消码:
30 搜不到酒店(任务会移出队列,后续不会再领取到)
31 满房(任务会移出队列,后续不会再领取到)
task_data 为任务返回的数据json,唯一码与领取任务时保持一致
'''
# task_data = task
# cancel_resp = cancel_one_task(VENDOR, USER, PWD, clientid, task_data, 30)
# print(cancel_resp)
File diff suppressed because it is too large Load Diff
@@ -0,0 +1 @@
function _typeof(o){return module.exports=_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o},_typeof(o)}module.exports=_typeof;
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,632 @@
// 真实浏览器环境 shim:按 SDK 实际需要铺开 navigator/screen/document/window 等
// 目标:属性做成自有可枚举属性(SDK 会用 hasOwnProperty / Object.keys 反查伪造)
import { createRequire } from 'node:module';
const require = createRequire(import.meta.url);
// 环境完全由调用方传入的 profile 决定,本文件不再内置任何"默认身份"
let CUR = null; // 当前正在构建的 profile(供 makeElement/makeCanvas 这类异步路径取用)
function need(profile, k) {
if (profile == null || profile[k] === undefined || profile[k] === '') throw new Error('缺 profile.' + k);
return profile[k];
}
// 真实网络开关:默认关闭(离线);WR_NET=1 时按真实浏览器行为请求 SDK 引导接口
const NET_ON = process.env.WR_NET === '1';
const netLog = [];
function httpRequest(method, url, headers, body) {
return new Promise((resolve) => {
if (!NET_ON) { netLog.push(method + ' ' + url + ' (stubbed)'); return resolve({ status: 0, text: '' }); }
const u = new URL(url);
const lib = u.protocol === 'http:' ? require('node:http') : require('node:https');
const req = lib.request({ method, hostname: u.hostname, port: u.port || (u.protocol === 'http:' ? 80 : 443), path: u.pathname + u.search, headers }, (res) => {
let data = '';
res.on('data', (c) => { data += c; });
res.on('end', () => { netLog.push(method + ' ' + url + ' -> ' + res.statusCode + ' len=' + data.length); resolve({ status: res.statusCode, text: data }); });
});
req.on('error', (e) => { netLog.push(method + ' ' + url + ' ERR ' + e.message); resolve({ status: 0, text: '' }); });
if (body) req.write(body);
req.end();
});
}
// 方法必须挂在 prototype 上:H5guard.init 会 hook XMLHttpRequest.prototype.open/send
// 来给白名单域名自动加签(GET 拼进 url),用实例属性的话钩子挂不上、只会走手动 sign() 那条路
function makeXHR(ua) {
function XMLHttpRequest() {
this.readyState = 0; this.status = 0; this.responseText = ''; this.response = ''; this.responseType = '';
this._headers = {};
this.onreadystatechange = null; this.onload = null; this.onerror = null;
this._m = null; this._u = null;
}
XMLHttpRequest.prototype.open = function (m, u) { this._m = m; this._u = u; this.readyState = 1; if (this.onreadystatechange) this.onreadystatechange(); };
XMLHttpRequest.prototype.setRequestHeader = function (k, v) { this._headers[k] = v; };
XMLHttpRequest.prototype.getAllResponseHeaders = function () { return ''; };
XMLHttpRequest.prototype.getResponseHeader = function () { return null; };
XMLHttpRequest.prototype.addEventListener = function (t, f) { if (t === 'load') this.onload = f; if (t === 'readystatechange') this.onreadystatechange = f; };
XMLHttpRequest.prototype.send = function (body) {
const xhr = this;
httpRequest(xhr._m || 'GET', xhr._u, Object.assign({ 'user-agent': ua }, xhr._headers), body).then((r) => {
xhr.status = r.status; xhr.responseText = r.text;
xhr.response = xhr.responseType === 'json' ? (() => { try { return JSON.parse(r.text); } catch { return null; } })() : r.text;
xhr.readyState = 4;
if (xhr.onreadystatechange) xhr.onreadystatechange();
if (xhr.onload) xhr.onload();
});
};
XMLHttpRequest.prototype.abort = function () {};
return XMLHttpRequest;
}
function makeFetch(ua) {
return (u, o) => {
const url = typeof u === 'string' ? u : (u && u.url);
const method = (o && o.method) || 'GET';
return httpRequest(method, url, Object.assign({ 'user-agent': ua }, (o && o.headers) || {}), o && o.body).then((r) => ({
ok: r.status >= 200 && r.status < 300, status: r.status, headers: { get: () => null },
text: () => Promise.resolve(r.text), json: () => Promise.resolve(JSON.parse(r.text || 'null')),
}));
};
}
export function netCalls() { return netLog.slice(); }
function makeCanvas2d(canvas) {
const ctx = {
canvas, font: '10px sans-serif', textBaseline: 'alphabetic', textAlign: 'start', direction: 'ltr',
fillStyle: '#000000', strokeStyle: '#000000', globalAlpha: 1, globalCompositeOperation: 'source-over',
lineWidth: 1, lineCap: 'butt', lineJoin: 'miter', shadowBlur: 0, shadowColor: 'rgba(0, 0, 0, 0)',
imageSmoothingEnabled: true, miterLimit: 10, lineDashOffset: 0,
save() {}, restore() {}, scale() {}, rotate() {}, translate() {}, transform() {}, setTransform() {}, resetTransform() {},
beginPath() {}, closePath() {}, moveTo() {}, lineTo() {}, bezierCurveTo() {}, quadraticCurveTo() {}, arc() {}, arcTo() {}, rect() {}, ellipse() {},
fill() {}, stroke() {}, clip() {}, fillRect() {}, strokeRect() {}, clearRect() {}, drawImage() {},
fillText() {}, strokeText() {}, setLineDash() {}, getLineDash: () => [],
createLinearGradient: () => ({ addColorStop() {} }), createRadialGradient: () => ({ addColorStop() {} }),
createPattern: () => ({}), isPointInPath: () => false,
measureText(t) {
const fam = (String(ctx.font).match(/[\d.]+px\s+(.+)$/) || [])[1] || '';
const text = String(t);
let perChar = 9;
if (/monospace|Courier|Consolas|Lucida Console/i.test(fam)) perChar = 9;
else if (WIN_FONTS.has(fam)) perChar = 8.4 + (strHash(fam) % 7) * 0.1;
return { width: Math.round(perChar * text.length * 10) / 10, actualBoundingBoxAscent: 8, actualBoundingBoxDescent: 2, actualBoundingBoxLeft: 0, actualBoundingBoxRight: perChar * text.length, fontBoundingBoxAscent: 9, fontBoundingBoxDescent: 2 };
},
getContextAttributes: () => ({ alpha: true, colorSpace: 'srgb', desynchronized: false, willReadFrequently: false }),
getImageData(x, y, w, h) {
const data = new Uint8ClampedArray(w * h * 4);
for (let i = 0; i < data.length; i += 4) { data[i] = (i * 7) & 255; data[i + 1] = (i * 13) & 255; data[i + 2] = (i * 29) & 255; data[i + 3] = 255; }
return { data, width: w, height: h };
},
putImageData() {}, createImageData: (w, h) => ({ data: new Uint8ClampedArray(w * h * 4), width: w, height: h }),
};
return ctx;
}
function makeWebGL() {
const ext = { UNMASKED_VENDOR_WEBGL: 37445, UNMASKED_RENDERER_WEBGL: 37446, WEBGL_debug_renderer_info: true };
// 参数与扩展列表按真实浏览器实测镜像(GTX 1060 / NVIDIA / Chrome 153)
const params = {
7936: 'WebKit', 7937: 'WebKit WebGL', 7938: 'WebGL 1.0 (OpenGL ES 2.0 Chromium)',
35724: 'WebGL GLSL ES 1.0 (OpenGL ES GLSL ES 1.0 Chromium)',
37445: (CUR && CUR.glVendor) || '',
37446: (CUR && CUR.glRenderer) || '',
3379: 16384, 34076: 16384, 34930: 16, 35660: 16, 3386: 32767, 3413: 8, 33901: [1024, 1024], 33902: [1, 1],
34921: 16, 36347: 1024, 36348: 32, 36349: 1024, 34024: 16384, 34047: 16, 34852: 16, 34853: 8, 34854: 8,
36006: 4096, 36007: 4096, 35375: [16384, 16384], 35376: 16384, 35661: 32, 32883: 0, 33001: [1, 8192],
};
return {
canvas: { width: (CUR && CUR.screenWidth) || 0, height: (CUR && CUR.screenHeight) || 0 },
drawingBufferWidth: (CUR && CUR.screenWidth) || 0, drawingBufferHeight: (CUR && CUR.screenHeight) || 0, drawingBufferColorSpace: 'srgb', unpackColorSpace: 'srgb',
// WebGL 常量(SDK 用 gl.VERSION / gl.RENDERER 这类常量去 getParameter,缺了会拿到 undefined)
VERSION: 7938, RENDERER: 7937, VENDOR: 7936, SHADING_LANGUAGE_VERSION: 35724, MAX_TEXTURE_SIZE: 3379,
MAX_RENDERBUFFER_SIZE: 34024, MAX_VIEWPORT_DIMS: 3386, MAX_VERTEX_ATTRIBS: 34921, MAX_TEXTURE_IMAGE_UNITS: 34930,
MAX_VERTEX_TEXTURE_IMAGE_UNITS: 35660, MAX_COMBINED_TEXTURE_IMAGE_UNITS: 35661, MAX_CUBE_MAP_TEXTURE_SIZE: 34076,
MAX_FRAGMENT_UNIFORM_VECTORS: 36349, MAX_VERTEX_UNIFORM_VECTORS: 36347, MAX_VARYING_VECTORS: 36348,
DEPTH_BUFFER_BIT: 256, STENCIL_BUFFER_BIT: 1024, COLOR_BUFFER_BIT: 16384,
getExtension: (n) => (n === 'WEBGL_debug_renderer_info' ? ext : (n === 'EXT_texture_filter_anisotropic' ? { MAX_TEXTURE_MAX_ANISOTROPY_EXT: 34047 } : (n === 'WEBGL_lose_context' ? { loseContext() {}, restoreContext() {} } : {}))),
getSupportedExtensions: () => ['ANGLE_instanced_arrays', 'EXT_blend_minmax', 'EXT_clip_control', 'EXT_color_buffer_half_float', 'EXT_depth_clamp', 'EXT_disjoint_timer_query', 'EXT_float_blend', 'EXT_frag_depth', 'EXT_polygon_offset_clamp', 'EXT_shader_texture_lod', 'EXT_texture_compression_bptc', 'EXT_texture_compression_rgtc', 'EXT_texture_filter_anisotropic', 'EXT_texture_mirror_clamp_to_edge', 'EXT_sRGB', 'KHR_parallel_shader_compile', 'OES_element_index_uint', 'OES_fbo_render_mipmap', 'OES_standard_derivatives', 'OES_texture_float', 'OES_texture_float_linear', 'OES_texture_half_float', 'OES_texture_half_float_linear', 'OES_vertex_array_object', 'WEBGL_blend_func_extended', 'WEBGL_color_buffer_float', 'WEBGL_compressed_texture_s3tc', 'WEBGL_compressed_texture_s3tc_srgb', 'WEBGL_debug_renderer_info', 'WEBGL_debug_shaders', 'WEBGL_depth_texture', 'WEBGL_draw_buffers', 'WEBGL_lose_context', 'WEBGL_multi_draw', 'WEBGL_polygon_mode'],
getParameter: (p) => (p in params ? params[p] : 0),
getShaderPrecisionFormat: () => ({ rangeMin: 127, rangeMax: 127, precision: 23 }),
getContextAttributes: () => ({ alpha: true, antialias: true, depth: true, premultipliedAlpha: true, preserveDrawingBuffer: false, stencil: false }),
createBuffer: () => ({}), createTexture: () => ({}), createProgram: () => ({}), createShader: () => ({}),
getProgramParameter: () => true, getShaderParameter: () => true, getShaderInfoLog: () => '', getProgramInfoLog: () => '',
getUniformLocation: () => ({}), getAttribLocation: () => 0, getError: () => 0,
};
}
// canvas.toDataURL 返回真实浏览器同一套绘制结果的 PNG(按实测镜像,1246 字符)
const REAL_CANVAS_PNG = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB4AAAAeCAYAAAA7MK6iAAADSUlEQVR4AayXTUhUURTHzx2zD01yk2DRx8LJfUO0U4Q2RWBQm4JAwZKCFhVRFJGbMmrXZtCI3LTKICFq0SIh2iki9IEmRCVK5SbMCsum3//p6JvnvPl4M/L/33Puuefe/71n3tw3xiyVSnl80Zuytgp8K44fmNPFXBaxIhgz/fXdMGs5ada8oF5udjLsZzdzxpibcAwUzpgN3jVrv8IksBNGQQ2TdsEtsEDErOXUSmpUYa0g8WYcWcwKVIVtdGvhCig1pUr3SxHWGhJNyPFzEx0d7igWOVqzSot5Nt3swFmzRPlH8PtgMagnOaPk3wn0wIfwHxT2BIQ/EVQBRPmP6LdDbUIb+ImfDzq1xJfzUngf4QxMozYgnI4HrTahDewNDoT067czUAWF9TQX4AG4Dp6HrQUKk+rhNe0rmA81Ol0rWXqwMMuYx+uFo0UKM8Xe0IzDnNBn0kDGRuiHyj5LYD6CMNNsSE0O1uika0mogNmR+VRnz1kd/UEo16ln9dXoJ2kOZkc0Ya2lB1U2G6f/EB2FsphVWIhYai30TU0IpzYwUAfDMFWCcHgVzabPodgIQ5AYLkE4ZE0brzSb7Wb0JRR+09yGTyHQrZaYkXD4k0daOKpDhob1uaavxkCO7vGDizEeruSiV2y7OcuEJ8T0NcVkQNeoBCW8NIDwCdzrsEjo/vZPGaQzBf2QoMT0YlKJfWMIq3eZRldZgWXX/aCTSUhWJ51mCQlJQGI6oQTlMxTEkrDCOvlbnGMwD3TzDZOTFkuLSEi+xLQBUsLgE1aKfr88wBmDKv8+rN5xqoSIv5VYF2MpcobYQU80BoTR8aANqPzP6amef7HwDP4ksWsaUw7hiIjtr7Nfeefq9XqfrDuwPBiIPfvqquI3bcQOs6IEVFFRvmIS1L3cxnh5MGDOHfJK/f6S2239ljQJUFET5esFUz5B4y9piGJ1c8lA507TdkD9OsOUFVqzA1FpeAt7J/Y8Nc7dw+h2T2LLBa3ViKjWXl4zU1hh576QpJ3F6d6Ck7BYaI7mxr21WPP4qFV3jlj87GfTO9NX6uDSzk0w6SLUvwFNDF+Fj+E7qNLpTSDKV0xjymny5jinuRPkmsQqF6zBUlY1x7EU+w8AAP//KN+TZgAAAAZJREFUAwDN3O/Xd4c5tQAAAABJRU5ErkJggg==';
function makeCanvas() {
const canvas = {
width: 300, height: 150, style: {},
setAttribute() {}, appendChild() {}, addEventListener() {}, removeEventListener() {},
};
const gl = makeWebGL();
const ctx2d = makeCanvas2d(canvas);
canvas.getContext = (t) => (/webgl/i.test(t) ? gl : ctx2d);
canvas.toDataURL = () => REAL_CANVAS_PNG;
return canvas;
}
let scriptRunner = null;
let dumpHook = null;
export function setDumpHook(fn) { dumpHook = fn; }
export function setScriptRunner(fn) { scriptRunner = fn; }
function appendNode(c) { if (c && c.tagName === 'SCRIPT' && c.src) loadScript(c); return c; }
// 字体检测依赖 offsetWidth:给元素补上基于 innerHTML 的伪布局度量,让字体探测能"测出"字体
const WIN_FONTS = new Set(['Arial', 'Times New Roman', 'Courier New', 'Verdana', 'Georgia', 'Tahoma', 'Trebuchet MS', 'Comic Sans MS', 'Impact', 'Webdings', 'Wingdings', 'Segoe UI', 'Calibri', 'Cambria', 'Consolas', 'Microsoft YaHei', 'SimSun', 'SimHei', 'KaiTi', 'FangSong', 'Microsoft JhengHei', 'MS Gothic', 'Lucida Console', 'Palatino Linotype', 'Book Antiqua', 'Century Gothic', 'Gabriola', 'Candara', 'Corbel', 'Franklin Gothic Medium', 'Constantia', 'Segoe Print', 'Segoe Script', 'Sylfaen', 'Marlett', 'MS Sans Serif', 'MS Serif', 'Fixedsys', 'System', 'Terminal', 'Modern', 'Roman', 'Script', 'Small Fonts', 'Lucida Sans Unicode']);
function strHash(s) { let h = 0; for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) | 0; return Math.abs(h); }
// 元素宽度:优先按 style.fontFamily 度量(SDK 的字体检测就是给 span 设 fontFamily 再量宽)
// 比例表按真实浏览器对 31 个候选字体的实测宽度镜像(base sans-serif=727)
const FONT_RATIO = { monospace: 468 / 727, serif: 468 / 727, 'sans-serif': 1, Arial: 648 / 727, 'Arial Black': 792 / 727, 'Arial Hebrew': 1, 'Arial MT': 1, 'Arial Narrow': 531 / 727, 'Arial Rounded MT Bold': 1, 'Arial Unicode MS': 1, Cambria: 658 / 727, 'Cambria Math': 658 / 727, 'Comic Sans MS': 619 / 727, Consolas: 515 / 727, Courier: 562 / 727, 'Courier New': 562 / 727, Georgia: 697 / 727, Helvetica: 648 / 727, 'Helvetica Neue': 1, Impact: 614 / 727, 'Microsoft YaHei': 732 / 727, 'PingFang SC': 1, 'Segoe Print': 802 / 727, 'Segoe Script': 815 / 727, 'Segoe UI': 672 / 727, 'Segoe UI Light': 636 / 727, 'Segoe UI Semibold': 694 / 727, 'Segoe UI Symbol': 672 / 727, SimHei: 468 / 727, SimSun: 468 / 727, Tahoma: 654 / 727, 'Times New Roman': 620 / 727, 'Trebuchet MS': 661 / 727, Verdana: 760 / 727 };
function measureElement(el) {
const text = String(el._html || '').replace(/<[^>]*>/g, '').replace(/&[#\w]+;/g, 'x') || 'yodaaaaaaa';
const famRaw = el.style && el.style.fontFamily ? String(el.style.fontFamily) : '';
const size = parseFloat((el.style && el.style.fontSize) || 16) || 16;
if (!famRaw) return measureHtml(el._html);
const fam = famRaw.split(',')[0].replace(/['"]/g, '').trim();
const ratio = fam in FONT_RATIO ? FONT_RATIO[fam] : 1;
return Math.round(51.93 * ratio * (size / 72) * text.length * 100) / 100;
}
function measureHtml(html) { const text = String(html).replace(/<[^>]*>/g, ' ').replace(/&#(\d+);/g, (m, d) => String.fromCharCode(Number(d))).replace(/\s+/g, ' ').trim();
const fam = (String(html).match(/font[^>]*face\s*=\s*['"]?([^'">\s]+)/i) || [])[1] || '';
if (fam === 'monospace') return Math.round(text.length * 9 * 10) / 10;
if (fam === 'sans-serif' || fam === 'serif') return Math.round(text.length * 9 * 10) / 10;
if (WIN_FONTS.has(fam)) return Math.round((8.4 + (strHash(fam) % 7) * 0.1) * text.length * 10) / 10;
return Math.round(text.length * 9 * 10) / 10;
}
// document.createElement('script') + appendChild → 真实拉取并执行,SDK 靠这个加载采集包
function loadScript(el) {
if (!el || !el.src) return;
httpRequest('GET', el.src, { 'user-agent': (CUR && CUR.ua) || '' }).then((r) => {
netLogPush('script ' + el.src + ' -> ' + r.status + ' len=' + r.text.length);
if (r.status === 200 && r.text && scriptRunner) {
try { scriptRunner(r.text, el.src); } catch (e) { netLogPush('script ERR ' + el.src + ' ' + e.message); }
}
if (el.onload) el.onload();
if (el.onreadystatechange) el.onreadystatechange();
});
}
function netLogPush(s) { netLog.push(s); if (process.env.WR_NET_VERBOSE === '1') console.error('[net] ' + s); }
function makeElement(tag) {
if (tag === 'canvas') return makeCanvas();
if (tag === 'audio' || tag === 'video') return { tagName: String(tag).toUpperCase(), canPlayType: () => 'probably', play() {}, load() {}, setAttribute() {}, style: {} };
const el = {
tagName: String(tag).toUpperCase(), style: {}, children: [],
setAttribute(k, v) { if (k === 'src') { el._src = v; loadScript(el); } },
getAttribute: () => null,
appendChild(c) { el.children.push(c); return c; },
addEventListener() {}, removeEventListener() {}, getContext: () => null, value: '',
_html: '',
get innerHTML() { return el._html; },
set innerHTML(v) { el._html = String(v); },
get textContent() { return el._html.replace(/<[^>]*>/g, ''); },
set textContent(v) { el._html = String(v); },
get offsetWidth() { return measureElement(el); },
get offsetHeight() { return el._html ? 16 : 0; },
get clientWidth() { return measureElement(el); },
get scrollWidth() { return measureElement(el); },
get clientHeight() { return el.offsetHeight; },
getBoundingClientRect() { return { width: el.offsetWidth, height: el.offsetHeight, top: 0, left: 0, right: el.offsetWidth, bottom: el.offsetHeight }; },
remove() {}, removeChild() {}, insertBefore(c) { return c; },
};
if (tag === 'script') {
Object.defineProperty(el, 'src', {
set(v) { el._src = v; loadScript(el); },
get() { return el._src || ''; },
});
}
return el;
}
// 最小内存版 IndexedDB:SDK 把指纹(dfp_h5_finger)缓存在这里,缺了它会退化成最短指纹
function makeRequest() {
const req = { result: undefined, error: null, onsuccess: null, onerror: null, readyState: 'pending' };
req._fire = (val) => { req.result = val; req.readyState = 'done'; setTimeout(() => { if (req.onsuccess) req.onsuccess({ target: req }); }, 0); };
req._fail = (e) => { req.error = e; setTimeout(() => { if (req.onerror) req.onerror({ target: req }); }, 0); };
return req;
}
function makeIndexedDB() {
const dbs = new Map();
function makeStore(map) {
return {
put(value, key) { const req = makeRequest(); map.set(key === undefined ? value.id : key, value); req._fire(key); return req; },
add(value, key) { const req = makeRequest(); map.set(key === undefined ? value.id : key, value); req._fire(key); return req; },
get(key) { const req = makeRequest(); req._fire(map.get(key)); return req; },
getAll() { const req = makeRequest(); req._fire([...map.values()]); return req; },
delete(key) { const req = makeRequest(); map.delete(key); req._fire(undefined); return req; },
clear() { const req = makeRequest(); map.clear(); req._fire(undefined); return req; },
count() { const req = makeRequest(); req._fire(map.size); return req; },
openCursor() { const req = makeRequest(); req._fire(null); return req; },
createIndex() { return {}; },
index() { return { get: () => makeRequest(), getAll: () => { const r = makeRequest(); r._fire([]); return r; }, openCursor: () => { const r = makeRequest(); r._fire(null); return r; } }; },
};
}
function makeDb(name) {
let db = dbs.get(name);
if (db) return db;
const stores = new Map();
db = {
name, version: 1, objectStoreNames: { contains: (n) => stores.has(n), length: 0 },
createObjectStore(n, opts) { const map = new Map(); stores.set(n, map); const st = makeStore(map); st.keyPath = (opts && opts.keyPath) || null; return st; },
transaction(names) {
const list = Array.isArray(names) ? names : [names];
const tx = { objectStore: (n) => { if (!stores.has(n)) stores.set(n, new Map()); return makeStore(stores.get(n)); }, oncomplete: null, onerror: null, onabort: null, mode: 'readwrite' };
setTimeout(() => { if (tx.oncomplete) tx.oncomplete(); }, 0);
return tx;
},
close() {}, deleteObjectStore(n) { stores.delete(n); },
onclose: null, onerror: null, onversionchange: null, _stores: stores,
};
dbs.set(name, db);
return db;
}
return {
open(name) {
const req = makeRequest();
const db = makeDb(name);
req.result = db;
setTimeout(() => {
if (req.onupgradeneeded) req.onupgradeneeded({ target: req });
req.readyState = 'done';
if (req.onsuccess) req.onsuccess({ target: req });
}, 0);
return req;
},
deleteDatabase(name) { const req = makeRequest(); dbs.delete(name); req._fire(undefined); return req; },
databases: () => Promise.resolve([...dbs.keys()].map((n) => ({ name: n, version: 1 }))),
};
}
// 音频指纹:OfflineAudioContext 需要正确的 oncomplete/startRendering 语义,否则 SDK 会反复重试
function makeAudioParam(v) { return { value: v, defaultValue: v, setValueAtTime() { return this; }, linearRampToValueAtTime() { return this; }, exponentialRampToValueAtTime() { return this; }, setTargetAtTime() { return this; } }; }
function makeAudioNode() { return { connect() {}, disconnect() {}, start() {}, stop() {}, channelCount: 2, numberOfInputs: 1, numberOfOutputs: 1 }; }
function makeOfflineAudioContext() {
let oacN = 0;
return function OfflineAudioContext(channels, length, sampleRate) {
const ctx = this;
if (process.env.WR_OAC_DBG === '1' && oacN++ < 5) console.error('[OAC] ctor args=', channels, length, sampleRate);
ctx.numberOfChannels = channels || 1;
ctx.length = length || 44100;
ctx.sampleRate = sampleRate || 44100;
ctx.currentTime = 0;
ctx.state = 'suspended';
ctx.destination = makeAudioNode();
ctx.oncomplete = null;
ctx.listener = {};
ctx.createOscillator = () => { const n = makeAudioNode(); n.type = 'sine'; n.frequency = makeAudioParam(1000); return n; };
ctx.createGain = () => { const n = makeAudioNode(); n.gain = makeAudioParam(1); return n; };
ctx.createDynamicsCompressor = () => { const n = makeAudioNode(); n.threshold = makeAudioParam(-24); n.knee = makeAudioParam(30); n.ratio = makeAudioParam(12); n.attack = makeAudioParam(0.003); n.release = makeAudioParam(0.25); return n; };
ctx.createAnalyser = () => { const n = makeAudioNode(); n.fftSize = 2048; n.frequencyBinCount = 1024; n.getFloatFrequencyData = () => {}; n.getByteFrequencyData = () => {}; return n; };
ctx.createBufferSource = () => makeAudioNode();
ctx.createBiquadFilter = () => { const n = makeAudioNode(); n.frequency = makeAudioParam(350); n.Q = makeAudioParam(1); n.type = 'lowpass'; return n; };
ctx.createScriptProcessor = () => makeAudioNode();
ctx.decodeAudioData = () => Promise.reject(new Error('decode error'));
ctx.resume = () => Promise.resolve();
ctx.suspend = () => Promise.resolve();
ctx.startRendering = () => {
if (process.env.WR_OAC_DBG === '1' && oacN < 8) console.error('[OAC] startRendering called');
const buf = {
numberOfChannels: ctx.numberOfChannels, length: ctx.length, sampleRate: ctx.sampleRate,
duration: ctx.length / ctx.sampleRate,
getChannelData: (c) => { const a = new Float32Array(ctx.length); for (let i = 0; i < a.length; i++) a[i] = Math.sin(i * 0.01 + c) * 0.001; return a; },
copyFromChannel() {}, copyToChannel() {},
};
ctx.state = 'closed';
return Promise.resolve(buf).then((b) => { setTimeout(() => { if (ctx.oncomplete) ctx.oncomplete({ target: ctx, renderedBuffer: b }); }, 0); return b; });
};
};
}
function makeStorage() { const m = new Map();
return {
getItem: (k) => (m.has(k) ? m.get(k) : null),
setItem: (k, v) => m.set(k, String(v)),
removeItem: (k) => m.delete(k),
clear: () => m.clear(),
key: (i) => [...m.keys()][i] ?? null,
get length() { return m.size; },
};
}
// WebRTC:SDK 会收 ICE 候选做指纹;候选按真实浏览器实测值镜像(mDNS .local)
function makeRTCPeerConnection() {
const CANDS = [
'candidate:3398552092 1 udp 2113937151 21ba7413-c3fc-4838-aa74-a2d93314734b.local 51283 typ host generation 0 ufrag QIYF network-cost 999',
'candidate:1378190728 1 udp 2113939711 04f0c44d-87bc-4da2-9f6a-1be12e4020ee.local 51284 typ host generation 0 ufrag QIYF network-cost 999',
];
return function RTCPeerConnection() {
const pc = this;
pc.localDescription = null; pc.iceGatheringState = 'new'; pc.connectionState = 'new'; pc.signalingState = 'stable';
pc.onicecandidate = null; pc.onicegatheringstatechange = null;
pc.createDataChannel = () => ({ close() {}, send() {}, addEventListener() {} });
pc.createOffer = () => Promise.resolve({ type: 'offer', sdp: 'v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=group:BUNDLE 0\r\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\na=ice-ufrag:QIYF\r\na=ice-pwd:abcdefghijklmnopqrstuvwx\r\n' });
pc.setLocalDescription = (d) => {
pc.localDescription = d; pc.iceGatheringState = 'gathering';
setTimeout(() => {
for (const c of CANDS) if (pc.onicecandidate) pc.onicecandidate({ candidate: { candidate: c } });
if (pc.onicecandidate) pc.onicecandidate({ candidate: null });
pc.iceGatheringState = 'complete';
if (pc.onicegatheringstatechange) pc.onicegatheringstatechange();
}, 0);
return Promise.resolve();
};
pc.setRemoteDescription = () => Promise.resolve();
pc.createAnswer = () => Promise.resolve({ type: 'answer', sdp: '' });
pc.addIceCandidate = () => Promise.resolve();
pc.getStats = () => Promise.resolve(new Map());
pc.addEventListener = () => {}; pc.removeEventListener = () => {};
pc.close = () => {};
};
}
function makeSpeechSynthesis() {
const V = [
{ voiceURI: 'Microsoft Huihui - Chinese (Simplified, PRC)', name: 'Microsoft Huihui - Chinese (Simplified, PRC)', lang: 'zh-CN', localService: true, default: true },
{ voiceURI: 'Microsoft Kangkang - Chinese (Simplified, PRC)', name: 'Microsoft Kangkang - Chinese (Simplified, PRC)', lang: 'zh-CN', localService: true, default: false },
{ voiceURI: 'Microsoft Yaoyao - Chinese (Simplified, PRC)', name: 'Microsoft Yaoyao - Chinese (Simplified, PRC)', lang: 'zh-CN', localService: true, default: false },
];
return { getVoices: () => V.slice(), onvoiceschanged: null, speak() {}, cancel() {}, pause() {}, resume() {}, pending: false, speaking: false, paused: false, addEventListener() {}, removeEventListener() {} };
}
const BASE_BTOA = (s) => Buffer.from(s, 'binary').toString('base64');
function makeTextEncoder() {
return class TextEncoder {
constructor() { this.encoding = 'utf-8'; }
encode(input = '') {
const s = String(input);
if (dumpHook) { try { dumpHook(s); } catch (e) {} }
if (process.env.WR_DUMP_TE === '1' && s.length > 200) {
netLogPush('TE len=' + s.length + ' head=' + JSON.stringify(s.slice(0, 300)));
if (process.env.WR_TE_FILE && s.length > 1000) { try { require('node:fs').appendFileSync(process.env.WR_TE_FILE, s + '\n\n====\n\n'); } catch (e) { /* ignore */ } }
}
return Buffer.from(s, 'utf8');
}
encodeInto(input, dest) { const b = Buffer.from(String(input), 'utf8'); dest.set(b.subarray(0, dest.length)); return { read: input.length, written: Math.min(b.length, dest.length) }; }
};
}
// crypto:SDK 常用 getRandomValues 取 nonce、用 subtle.digest 做摘要;缺了会走降级分支
function makeCrypto() {
const nodeCrypto = require('node:crypto');
return {
getRandomValues: (arr) => { const b = nodeCrypto.randomBytes(arr.length); for (let i = 0; i < arr.length; i++) arr[i] = b[i]; return arr; },
randomUUID: () => nodeCrypto.randomUUID(),
subtle: {
digest: (alg, data) => Promise.resolve(nodeCrypto.createHash(String(alg).replace('-', '').toLowerCase()).update(Buffer.from(data)).digest().buffer),
encrypt: () => Promise.resolve(new ArrayBuffer(16)), decrypt: () => Promise.resolve(new ArrayBuffer(16)),
generateKey: () => Promise.resolve({}), importKey: () => Promise.resolve({}), exportKey: () => Promise.resolve(new ArrayBuffer(32)),
sign: () => Promise.resolve(new ArrayBuffer(32)), verify: () => Promise.resolve(true),
},
};
}
// WebAssembly 最小可用集合(SDK 会探测其存在性/能力)
function makeWebAssembly() {
return {
compile: () => Promise.resolve({}), instantiate: () => Promise.resolve({ instance: { exports: {} }, module: {} }),
validate: () => true, Module: function () {}, Instance: function () {}, Memory: function (d) { this.buffer = new ArrayBuffer((d && d.initial ? d.initial : 1) * 65536); }, Table: function () {},
};
}
// 事件系统:SDK 会注册行为采集监听(click/mousemove/visibility…),
// 只给空 addEventListener 会让行为采集永远收不到事件,bio 上报也不会触发
const eventRegistry = new Map();
let envRef = null;
function addListener(type, fn) { if (typeof fn !== 'function') return; const list = eventRegistry.get(type) || []; if (!list.includes(fn)) list.push(fn); eventRegistry.set(type, list); }
function removeListener(type, fn) { const list = eventRegistry.get(type) || []; const i = list.indexOf(fn); if (i >= 0) list.splice(i, 1); }
export function dispatchEvent(type, extra = {}) {
const tgt = (envRef && envRef.document && envRef.document.body) || { nodeName: 'BODY', tagName: 'BODY' };
const evt = Object.assign({
type, target: tgt, currentTarget: tgt, srcElement: tgt, bubbles: true, cancelable: true, defaultPrevented: false,
timeStamp: Date.now(), isTrusted: true, button: 0, buttons: 0, detail: 1, view: envRef,
composedPath: () => [tgt, envRef && envRef.document, envRef],
preventDefault() {}, stopPropagation() {}, stopImmediatePropagation() {},
}, extra);
for (const fn of [...(eventRegistry.get(type) || [])]) { try { fn(evt); } catch (e) { if (process.env.WR_EVT_DBG === '1') console.error('[evt] ' + type + ' 监听器异常: ' + (e && e.message)); } }
const on = envRef && envRef['on' + type];
if (typeof on === 'function') { try { on(evt); } catch (e) {} }
}
export function installEventTargets(s) {
const t = {
addEventListener: (ty, fn) => addListener(ty, fn),
removeEventListener: (ty, fn) => removeListener(ty, fn),
dispatchEvent: (e) => { dispatchEvent(e && e.type || 'event', e); return true; },
};
Object.assign(s, t);
for (const k of ['document', 'body', 'head', 'documentElement']) {
const o = k === 'document' ? s.document : s.document[k];
if (o && typeof o === 'object') { o.addEventListener = t.addEventListener; o.removeEventListener = t.removeEventListener; }
}
}
export function buildEnv(profile) {
CUR = profile;
const ua = need(profile, 'ua');
const language = need(profile, 'language');
const languages = need(profile, 'languages');
const chBrandsRaw = need(profile, 'chBrands');
const chPlatform = String(need(profile, 'chPlatform')).replace(/"/g, '');
const chMobile = String(need(profile, 'chMobile')).replace('?', '') === '1';
const brands = [...String(chBrandsRaw).matchAll(/"([^"]+)";v="([^"]+)"/g)].map((m) => ({ brand: m[1], version: m[2] }));
const uaFull = (brands.find((b) => /Chromium|Google Chrome|Android WebView/i.test(b.brand)) || brands[0] || {}).version || '';
const arch = profile.architecture || '';
const bitness = profile.bitness || '';
const pVer = profile.platformVersion || '';
const sw = need(profile, 'screenWidth');
const sh = need(profile, 'screenHeight');
const availHeight = need(profile, 'availHeight');
const colorDepth = need(profile, 'colorDepth');
const dpr = need(profile, 'devicePixelRatio');
const origin = need(profile, 'origin');
const originHost = new URL(origin).hostname;
const nav = {
userAgent: ua,
appVersion: ua.replace('Mozilla/', ''),
appName: 'Netscape',
appCodeName: 'Mozilla',
product: 'Gecko',
productSub: '20030107',
vendor: 'Google Inc.',
vendorSub: '',
platform: need(profile, 'platform'),
language: language,
languages: languages,
cookieEnabled: true,
onLine: true,
doNotTrack: null,
webdriver: false,
hardwareConcurrency: need(profile, 'hardwareConcurrency'),
deviceMemory: need(profile, 'deviceMemory'),
maxTouchPoints: need(profile, 'maxTouchPoints'),
pdfViewerEnabled: true,
plugins: {
length: 5, 0: { name: 'PDF Viewer', filename: 'internal-pdf-viewer' }, 1: { name: 'Chrome PDF Viewer' }, 2: { name: 'Chromium PDF Viewer' }, 3: { name: 'Microsoft Edge PDF Viewer' }, 4: { name: 'WebKit built-in PDF' },
item: (i) => null, namedItem: () => null, refresh() {},
},
mimeTypes: { length: 2, 0: { type: 'application/pdf', suffixes: 'pdf' }, 1: { type: 'text/pdf', suffixes: 'pdf' }, item: () => null, namedItem: () => null },
userAgentData: (() => { const j = { architecture: arch, bitness: bitness, brands: brands.map((b) => b.brand + '-' + b.version).join('/'), mobile: chMobile ? 'true' : 'false', model: profile.model || '', pVersion: pVer, uVersion: uaFull, platform: chPlatform }; return { brands, mobile: chMobile, platform: chPlatform, architecture: arch, bitness: bitness, model: profile.model || '', platformVersion: pVer, uaFullVersion: uaFull, fullVersionList: brands.slice(), toJSON() { return j; }, getHighEntropyValues: () => Promise.resolve(j) }; })(),
connection: { effectiveType: '4g', rtt: 50, downlink: 10, saveData: false },
javaEnabled: () => false,
sendBeacon: (u, d) => { netLogPush('beacon ' + u + (d ? ' len=' + String(d).length : '')); return true; },
vibrate: () => false,
getBattery: () => Promise.resolve({ charging: true, chargingTime: 0, dischargingTime: Infinity, level: 1, addEventListener() {}, onchargingchange: null }),
geolocation: { getCurrentPosition: (ok) => ok && ok({ coords: { latitude: 23.12, longitude: 113.28, accuracy: 20 } }), watchPosition: () => 1, clearWatch() {} },
mediaDevices: { enumerateDevices: () => Promise.resolve([{ kind: 'audioinput', deviceId: 'default', groupId: 'g', label: '' }, { kind: 'videoinput', deviceId: 'v1', groupId: 'g', label: '' }]), getUserMedia: () => Promise.reject(new Error('NotAllowedError')) },
mediaCapabilities: { decodingInfo: () => Promise.resolve({ supported: true, smooth: true, powerEfficient: true }) },
permissions: { query: () => Promise.resolve({ state: 'prompt' }) },
storage: { estimate: () => Promise.resolve({ quota: 300000000000, usage: 0 }) },
clipboard: {}, credentials: {}, serviceWorker: {},
userActivation: { isActive: true, hasBeenActive: true },
mediaSession: { metadata: null, playbackState: 'none', setActionHandler() {} },
keyboard: { getLayoutMap: () => Promise.resolve(new Map([['KeyA', 'a'], ['Enter', 'Enter']])), lock: () => Promise.resolve(), unlock() {} },
locks: { request: () => Promise.resolve() },
presentation: { defaultRequest: null, receiver: null },
bluetooth: { getAvailability: () => Promise.resolve(false) },
usb: { getDevices: () => Promise.resolve([]) },
hid: { getDevices: () => Promise.resolve([]) },
serial: { getPorts: () => Promise.resolve([]) },
registerProtocolHandler() {},
msDoNotTrack: null, oscpu: undefined, cpuClass: undefined,
requestMediaKeySystemAccess: () => Promise.resolve({}),
getUserMedia: () => Promise.reject(new Error('NotAllowedError')),
webkitGetUserMedia: () => Promise.reject(new Error('NotAllowedError')),
// 浏览器 navigator 上还有的其余属性(Chrome 153),一并铺上,避免 SDK 探测时拿到 undefined 而跳过
gpu: { requestAdapter: () => Promise.resolve(null), getPreferredCanvasFormat: () => 'bgra8unorm', wgslLanguageFeatures: new Set() },
ink: { requestPresenter: () => Promise.resolve({}) },
login: { setStatus() {}, getStatus: () => Promise.resolve({}) },
managed: { getSupportedCommands: () => Promise.resolve([]) },
protectedAudience: {}, scheduling: { isInputPending: () => false },
serial: { getPorts: () => Promise.resolve([]), requestPort: () => Promise.reject(new Error('no')) },
storageBuckets: { getDirectory: () => Promise.resolve({}) },
virtualKeyboard: { boundingRect: { x: 0, y: 0, width: 0, height: 0 }, overlaysContent: false },
wakeLock: { request: () => Promise.resolve({ release: () => Promise.resolve(), addEventListener() {} }) },
windowControlsOverlay: { visible: false, getTitlebarAreaRect: () => ({ x: 0, y: 0, width: 0, height: 0 }), addEventListener() {} },
xr: { isSessionSupported: () => Promise.resolve(false), addEventListener() {} },
devicePosture: { type: 'continuous', onchange: null },
getGamepads: () => [],
getInstalledRelatedApps: () => Promise.resolve([]),
requestMIDIAccess: () => Promise.resolve({ inputs: new Map(), outputs: new Map(), sysexEnabled: false }),
unregisterProtocolHandler() {}, setAppBadge() {}, clearAppBadge() {},
clearOriginJoinedAdInterestGroups() {}, joinAdInterestGroup() {}, leaveAdInterestGroup() {},
adAuctionComponents() {}, canLoadAdAuctionFencedFrame: () => false, createAuctionNonce: () => '', deprecatedReplaceInURN() {},
deprecatedRunAdAuctionEnforcesKAnonymity: false, deprecatedURNToURL() {}, getInterestGroupAdAuctionData: () => Promise.resolve({}),
runAdAuction: () => Promise.resolve(null), updateAdInterestGroups() {},
webkitPersistentStorage: { queryUsageAndQuota: () => {}, requestQuota: () => {} },
webkitTemporaryStorage: { queryUsageAndQuota: () => {}, requestQuota: () => {} },
};
const screen = {
width: sw, height: sh, availWidth: sw, availHeight: availHeight,
colorDepth: colorDepth, pixelDepth: colorDepth, availLeft: 0, availTop: 0,
orientation: { type: sw >= sh ? 'landscape-primary' : 'portrait-primary', angle: 0, addEventListener() {}, onchange: null },
};
const docEl = { style: {}, clientWidth: sw, clientHeight: availHeight, getBoundingClientRect: () => ({ width: sw, height: availHeight, top: 0, left: 0 }) };
const document = {
cookie: '',
documentElement: docEl, head: { appendChild: appendNode }, body: { appendChild: appendNode, style: {}, removeChild() {}, insertBefore(c) { return c; } },
referrer: need(profile, 'referrer'), title: profile.title || '', characterSet: 'UTF-8', charset: 'UTF-8',
readyState: 'complete', visibilityState: 'visible', hidden: false, hasFocus: () => true,
createElement: makeElement,
createElementNS: (ns, tag) => makeElement(tag),
getElementsByTagName: () => [], getElementsByClassName: () => [], querySelector: () => null, querySelectorAll: () => [],
getElementById: () => null,
addEventListener() {}, removeEventListener() {}, createTextNode: (t) => ({ textContent: t }), createDocumentFragment: () => ({ appendChild() {} }),
fonts: { check: () => true, add() {}, delete() {}, forEach() {}, entries: () => [][Symbol.iterator](), values: () => [][Symbol.iterator](), keys: () => [][Symbol.iterator](), size: 0, ready: Promise.resolve(), status: 'loaded', onloadingdone: null, onloadingerror: null, addEventListener() {}, removeEventListener() {} },
};
const win = {
navigator: nav, screen, document,
location: { href: origin + '/', protocol: 'https:', host: originHost, hostname: originHost, origin: origin, pathname: '/', search: '', hash: '' },
innerWidth: need(profile, 'innerWidth'), innerHeight: need(profile, 'innerHeight'), outerWidth: sw, outerHeight: sh, devicePixelRatio: dpr,
screenX: 0, screenY: 0, screenLeft: 0, screenTop: 0, scrollX: 0, scrollY: 0, pageXOffset: 0, pageYOffset: 0,
localStorage: makeStorage(), sessionStorage: makeStorage(),
indexedDB: makeIndexedDB(),
caches: { open: () => Promise.resolve({ match: () => Promise.resolve(undefined), put: () => Promise.resolve(), addAll: () => Promise.resolve() }), keys: () => Promise.resolve([]), match: () => Promise.resolve(undefined) },
performance: { now: () => Date.now() - 1000, timeOrigin: Date.now() - 1000,
timing: (() => { const base = Date.now() - 3000; const t = {}; let off = 0; for (const k of ['navigationStart','unloadEventStart','unloadEventEnd','redirectStart','redirectEnd','fetchStart','domainLookupStart','domainLookupEnd','connectStart','connectEnd','secureConnectionStart','requestStart','responseStart','responseEnd','domLoading','domInteractive','domContentLoadedEventStart','domContentLoadedEventEnd','domComplete','loadEventStart','loadEventEnd']) t[k] = base + (off += 7) + (k.length % 5); return t; })(),
navigation: { type: 0, redirectCount: 0 },
getEntriesByType: () => [], getEntriesByName: () => [], getEntries: () => [], mark() {}, measure() {}, clearMarks() {}, clearMeasures() {}, memory: { jsHeapSizeLimit: 4395630592, totalJSHeapSize: 30000000, usedJSHeapSize: 20000000 }, getEntriesByType: () => [], getEntries: () => [], mark() {}, measure() {}, clearMarks() {}, now2: () => Date.now() },
XMLHttpRequest: makeXHR(ua),
fetch: makeFetch(ua),
matchMedia: (q) => ({ matches: false, media: q, addListener() {}, removeListener() {}, addEventListener() {}, onchange: null }),
requestAnimationFrame: (cb) => setTimeout(() => cb(Date.now()), 16),
cancelAnimationFrame: (id) => clearTimeout(id),
OfflineAudioContext: makeOfflineAudioContext(),
AudioContext: function () { return new win.OfflineAudioContext(); },
WebGLRenderingContext: function () {}, Image: function () {}, Worker: function () {}, MutationObserver: function () { this.observe = () => {}; this.disconnect = () => {}; },
// 浏览器原生对象:crypto/WebAssembly/各类 Observer 缺了会让 SDK 跳过部分采集
crypto: makeCrypto(),
WebAssembly: makeWebAssembly(),
queueMicrotask: (fn) => { Promise.resolve().then(fn); },
requestIdleCallback: (fn) => setTimeout(() => fn({ didTimeout: false, timeRemaining: () => 50 }), 1),
cancelIdleCallback: (id) => clearTimeout(id),
PerformanceObserver: function () { this.observe = () => {}; this.disconnect = () => {}; this.takeRecords = () => []; },
IntersectionObserver: function () { this.observe = () => {}; this.disconnect = () => {}; this.unobserve = () => {}; this.takeRecords = () => []; },
ResizeObserver: function () { this.observe = () => {}; this.disconnect = () => {}; this.unobserve = () => {}; },
ReportingObserver: function () { this.observe = () => {}; this.disconnect = () => {}; },
BroadcastChannel: function () { this.postMessage = () => {}; this.close = () => {}; this.addEventListener = () => {}; },
MessageChannel: function () { const p = { postMessage() {}, addEventListener() {}, start() {}, close() {} }; this.port1 = p; this.port2 = p; },
CSS: { supports: () => true, escape: (s) => s },
CSSStyleDeclaration: function () {}, HTMLCanvasElement: function () {}, Event: function (t) { this.type = t; }, CustomEvent: function (t) { this.type = t; },
screen_orientation_helper: undefined,
// 能力位图(k8/k100/k101)通常来自 typeof 探测,补齐常见浏览器接口
Audio: function () {}, Blob: class {}, URL: URL, URLSearchParams: URLSearchParams, FormData: class {}, Headers: class {}, Request: class {}, Response: class {}, AbortController: class { constructor() { this.signal = {}; } abort() {} }, EventSource: function () {}, FileReader: class {}, MediaSource: function () {}, SourceBuffer: function () {}, MediaKeys: function () {}, RTCDataChannel: function () {}, RTCRtpSender: function () {}, MediaStreamTrack: function () {}, MediaStream: function () {}, Notification: function () {}, PaymentRequest: function () {}, PublicKeyCredential: function () {}, Credential: function () {}, PointerEvent: function () {}, TouchEvent: function () {}, WheelEvent: function () {}, KeyboardEvent: function () {}, DragEvent: function () {}, DataTransfer: function () {}, ClipboardEvent: function () {}, BeforeUnloadEvent: function () {}, MessageEvent: function () {}, StorageEvent: function () {}, DeviceMotionEvent: function () {}, DeviceOrientationEvent: function () {}, GamepadEvent: function () {}, MediaQueryListEvent: function () {}, TransitionEvent: function () {}, AnimationEvent: function () {}, FocusEvent: function () {}, PopStateEvent: function () {}, HashChangeEvent: function () {}, ProgressEvent: function () {}, ErrorEvent: function () {}, CloseEvent: function () {}, PageTransitionEvent: function () {}, StorageManager: function () {}, Worklet: function () {}, AudioWorkletNode: function () {}, MediaRecorder: function () {}, SpeechRecognition: function () {}, webkitSpeechRecognition: function () {}, SharedWorker: function () {}, webkitMediaSource: function () {}, webkitURL: URL, mozGetUserMedia: undefined,
speechSynthesis: makeSpeechSynthesis(),
SpeechSynthesisUtterance: function (t) { this.text = t; this.lang = ''; this.voice = null; },
RTCPeerConnection: makeRTCPeerConnection(),
webkitRTCPeerConnection: makeRTCPeerConnection(),
addEventListener() {}, removeEventListener() {}, dispatchEvent: () => true, postMessage() {},
getComputedStyle: () => ({ getPropertyValue: () => '' }),
atob: (s) => Buffer.from(s, 'base64').toString('binary'),
btoa: (s) => { if (process.env.WR_DUMP_B64 === '1') { const buf = Buffer.from(String(s), 'binary'); netLog.push('BTOA len=' + buf.length + ' hex=' + buf.slice(0, 48).toString('hex') + ' ascii=' + JSON.stringify(buf.slice(0, 120).toString('utf8'))); } return BASE_BTOA(s); },
setTimeout, clearTimeout, setInterval, clearInterval,
console: { log() {}, warn() {}, error() {}, info() {}, debug() {} },
Date, Math, JSON, Promise, parseInt, parseFloat, isNaN, encodeURIComponent, decodeURIComponent, encodeURI, decodeURI, escape, unescape,
Uint8Array, Uint8ClampedArray, Uint16Array, Uint32Array, Int8Array, Int16Array, Int32Array, Float32Array, Float64Array, ArrayBuffer, DataView,
// 明文转字节入口:加密前 SDK 必须把明文交给 TextEncoder,钩住它就能拿到明文
TextEncoder: makeTextEncoder(),
TextDecoder, String, Number, Boolean, Array, Object, Function, Error, TypeError, RegExp, Map, Set, WeakMap, WeakSet, Symbol, Proxy, Reflect, BigInt,
};
win.self = win;
win.window = win;
win.globalThis = win;
win.top = win;
win.parent = win;
win.frames = win;
envRef = win;
installEventTargets(win);
return win;
}
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+282
View File
@@ -0,0 +1,282 @@
// 美团小程序 mtgsig —— 纯算法实现(不加载 jsguard 包、不补环境)
// 算法来源:wxde8ac0a21135c07d / wx-jsguard 2.5.0 静态逆向;在 flows 抓包上 a4/d1/a5 结构与公式已对齐
//
// mtgsig 字段:
// a1 = "1.2" a2 = 毫秒时间戳(=q 里的 s)
// a3 = dfpid a4 = 见 buildA4()
// a5 = 自定义base64( y(16B) ‖ RC4_y(JSON(qn)) ) a6 = "w1.x"+base64(AES-128-CBC(gzip(9项数组)))(当前纯写 w1.6)
// a7 = appid x0 = 3 d1 = 见 buildD1()
//
// 需要外部给的(算法里算不出来):dfpid / localId / filetime / 46 项设备画像 / 出签会话上下文。
// 须从一份抓包旧 mtgsig 解出(解密mtgsig.py 或 serve /derive);含 b9 开关串、反算 r、qn.b7/b8 等。
import crypto from 'node:crypto';
import zlib from 'node:zlib';
import { gzipSync } from './gzip-mini.mjs';
// ---------------- 基础算法 ----------------
// 与 jsguard 里的 ge() 等价的 MurmurHash3_x86_32(results 为有符号 Int32,用时 >>>0)
export function murmur3(bytes, seed) {
const e = bytes, n0 = e.length;
const mul = (x) => (1540483477 * (x & 65535) + ((1540483477 * (x >>> 16) & 65535) << 16)) >>> 0;
let n = n0, t = ((seed | 0) ^ n0) >>> 0, c = 0;
while (n >= 4) {
let r = ((e[c] & 255) | ((e[c + 1] & 255) << 8) | ((e[c + 2] & 255) << 16) | ((e[c + 3] & 255) << 24)) >>> 0;
r = mul(r);
r = mul((r ^ (r >>> 24)) >>> 0);
t = (mul(t) ^ r) >>> 0;
n -= 4; c += 4;
}
switch (n) {
case 3: t = (t ^ ((e[c + 2] & 255) << 16)) >>> 0;
case 2: t = (t ^ ((e[c + 1] & 255) << 8)) >>> 0;
case 1: t = mul((t ^ (e[c] & 255)) >>> 0);
}
t = (t ^ (t >>> 13)) >>> 0;
t = mul(t);
return (((t ^ (t >>> 15)) >>> 0) ^ 1540483477) >>> 0;
}
// jsguard 的 crc32 变体:反射多项式 0xEDB88320,初值 0xFFFFFFFF,末异或 306674911(即 0x12477CDF,不是标准的 0xFFFFFFFF)
const CRC_TABLE = (() => {
const t = [];
for (let r = 0; r < 256; r++) { let v = r; for (let k = 0; k < 8; k++) v = v & 1 ? (v >>> 1) ^ 3988292384 : v >>> 1; t[r] = v >>> 0; }
return t;
})();
export function crc32(bytes) {
let r = -1;
for (let i = 0; i < bytes.length; i++) r = CRC_TABLE[(r ^ bytes[i]) & 255] ^ (r >>> 8);
return ((306674911 ^ r) >>> 0);
}
// 自定义字母表的标准 base64(带 = 填充)
export const A5_ALPHA = 'ZmserbBoHQtNP+wOcza/LpngG8yJq42KWYj0DSfdikx3VT16IlUAFM97hECvuRX5';
export function b64alphaEncode(buf) {
let out = '';
for (let i = 0; i < buf.length; i += 3) {
const n = (buf[i] << 16) | ((buf[i + 1] || 0) << 8) | (buf[i + 2] || 0);
out += A5_ALPHA[(n >> 18) & 63] + A5_ALPHA[(n >> 12) & 63];
out += i + 1 < buf.length ? A5_ALPHA[(n >> 6) & 63] : '=';
out += i + 2 < buf.length ? A5_ALPHA[n & 63] : '=';
}
return out;
}
export function b64alpha(s) {
let buf = 0, nb = 0; const out = [];
for (const ch of String(s)) {
const v = A5_ALPHA.indexOf(ch);
if (v < 0) continue;
buf = (buf << 6) | v; nb += 6;
if (nb >= 8) { nb -= 8; out.push((buf >> nb) & 0xff); }
}
return Buffer.from(out);
}
// 与 jsguard 一致的 RC4 变体(KSA 里多加了 +31)
export function rc4Twist(key, data) {
const S = []; for (let i = 0; i < 256; i++) S[i] = i;
let j = 0;
for (let i = 0; i < 256; i++) { j = (j + S[i] + key[i % key.length] + 31) % 256; const t = S[i]; S[i] = S[j]; S[j] = t; }
const out = Buffer.alloc(data.length);
let i = 0; j = 0;
for (let k = 0; k < data.length; k++) {
i = (i + 1) % 256; j = (j + S[i]) % 256;
const t = S[i]; S[i] = S[j]; S[j] = t;
out[k] = data[k] ^ S[(S[i] + S[j]) % 256];
}
return out;
}
const be4 = (v) => Buffer.from([(v >>> 24) & 255, (v >>> 16) & 255, (v >>> 8) & 255, v & 255]);
const le4 = (v) => Buffer.from([v & 255, (v >>> 8) & 255, (v >>> 16) & 255, (v >>> 24) & 255]);
const u8 = (s) => Buffer.from(s, 'utf8');
const md5 = (b) => crypto.createHash('md5').update(b).digest();
const md5hex = (b) => md5(b).toString('hex');
const md5ints = (b) => { const x = md5(b); return [0, 1, 2, 3].map((i) => (x[i * 4] | x[i * 4 + 1] << 8 | x[i * 4 + 2] << 16 | x[i * 4 + 3] << 24) >>> 0); };
const hexInts = (a) => a.map((v) => le4(v).toString('hex')).join('');
// ---------------- a6 ----------------
// key/iv:w1.4(快驴 fpv 1.8.0)和 w1.6 都能用这套解开;换更大版本仍要再对一次样本
const A6_KEY = Buffer.from('z7Jut6Ywr2Pe5Nhx');
const A6_IV = Buffer.from('0807060504030201');
// 出签默认前缀。从旧包重出时用旧 a6 的前缀(w1.4 / w1.6),不要写死成 w1.6
export const A6_PREFIX = 'w1.6';
// 次版本号只取一位。\d+ 会把 base64 开头的数字吃进前缀,密文长度对不齐 16,AES 报 wrong final block length
export function a6PrefixOf(a6) {
const m = String(a6 || '').match(/^(w\d+\.\d)/);
return m ? m[1] : A6_PREFIX;
}
// arr = [app, dfpid, filetime, fpv, localid, system(46项), timestamp, ext(5项), sessionId]
// 用 jsguard 自带那套 gzip(gzip-mini.mjs 搬运版)而不是 zlib:zlib 压出来的流与真机不同,
// 搬过来的实现已实测与 jsguard 的 gzipSync 逐字节一致(含 MTIME=当前秒、OS=3 的头)。
export function buildA6(arr, mtimeSec, prefix) {
const sec = mtimeSec === undefined ? Math.floor(Date.now() / 1000) : mtimeSec;
const gz = gzipSync(u8(JSON.stringify(arr)), { mtime: sec * 1000 });
const c = crypto.createCipheriv('aes-128-cbc', A6_KEY, A6_IV);
return (prefix || A6_PREFIX) + Buffer.concat([c.update(Buffer.from(gz)), c.final()]).toString('base64');
}
export function parseA6(a6) {
const buf = Buffer.from(String(a6).slice(a6PrefixOf(a6).length), 'base64');
const d = crypto.createDecipheriv('aes-128-cbc', A6_KEY, A6_IV);
return JSON.parse(zlib.gunzipSync(Buffer.concat([d.update(buf), d.final()])).toString('utf8'));
}
// 由零件直接拼 a6(不传 timestamp 时用当前秒)
export function buildA6FromParts(o) {
const ts = o.timestamp === undefined ? Math.ceil(Date.now() / 1000) : o.timestamp;
return buildA6([
o.appid, o.dfpid, o.filetime, o.fpv, o.localid, o.sys, ts, o.ext, o.sessionId,
], ts, o.a6Prefix || A6_PREFIX);
}
// ---------------- qn(a5 里 RC4 的载荷,键的插入顺序要跟 SDK 一致)----------------
// b7 秒级时间(init 时写入) / b1 getAccountInfoSync / b6 openId / b8 出签序号
// b12 appid / b11 定位精度串 / b2 当前路由 / b9 开关位图 / b10 失败上报(有才写)
export function buildQn(o) {
const qn = {};
qn.b7 = o.initSec;
qn.b1 = { miniProgram: { appId: o.appid, envVersion: o.envVersion || 'release', version: o.appVersion } };
if (o.openId) qn.b6 = o.openId;
qn.b8 = o.seq;
qn.b12 = o.appid;
qn.b2 = o.route || '';
// b9:五位开关串,随环境变;22122 只是无旧包时的兜底,应优先用抓包 qn.b9
qn.b9 = o.switchState || '22122';
if (o.loc) qn.b11 = o.loc; // 实测 b11 排在最后(不是赋值顺序)
if (o.failReports && o.failReports.length) qn.b10 = o.failReports;
return qn;
}
export function decodeQn(a5) {
const w = b64alpha(a5);
return JSON.parse(rc4Twist(w.slice(0, 16), w.slice(16)).toString('utf8'));
}
// ---------------- a5 ----------------
// y = md5(utf8(a6) ‖ BE32(low32(a2)))[0:7] ‖ [255&(r^crc32(l))] ‖ l ‖ BE32(crc32(y[0:12]))
// r 默认 1 仅防忘传;真机 appservice 常见反算为 0,须用 y[7]^crc32(BE32(a2低32)) 从旧包取
export function buildA5(a6, a2, qn, r = 1) {
const l = be4(a2 >>> 0);
const v = md5hex(Buffer.concat([u8(a6), l]));
const y = Buffer.from(v.slice(0, 14), 'hex'); // 7 字节
return (() => {
const buf = Buffer.alloc(16);
y.copy(buf, 0);
buf[7] = (r ^ crc32(l)) & 255;
l.copy(buf, 8);
be4(crc32(buf.slice(0, 12))).copy(buf, 12);
return b64alphaEncode(Buffer.concat([buf, rc4Twist(buf, u8(JSON.stringify(qn)))]));
})();
}
// ---------------- a4 / d1 ----------------
// z = utf8("METHOD path 规范化query") ‖ utf8(body前16200字节);x = murmur3(z, a2)
// query:按 & 切开,+ 当空格,decode 后再用 fe(encodeURIComponent 再编码 !'()*)重编码,按 [key, value] 排序。
// 不看接口路径。url 里如果已经带着 mtgsig,会算进去;重出签前先把这个参数从 url 去掉。
// body:GET/HEAD 不带。字符串原样(调用方已经编好的表单/JSON 都走这条)。
// 对象 + content-type 含 json → JSON.stringify。
// 其它对象 → 按插入顺序做 encodeURIComponent(不排序、不编码 !'()*),这是表单对象。
// 非 GET 的 body 只取前 16200 字节参与哈希,发出去的 body 本身不要截。
const BODY_LIMIT = 16200;
// query 用。比 encodeURIComponent 多编码 ! ' ( ) *
export function feQuery(s) {
return encodeURIComponent(s).replace(/[!'()*]/g, (c) => '%' + c.charCodeAt(0).toString(16).toUpperCase());
}
function decComponent(s) {
const t = String(s).replace(/\+/g, ' ');
try { return decodeURIComponent(t); } catch (e) { return t; }
}
function parsePairs(q) {
const out = [];
for (const part of String(q || '').split('&')) {
if (!part) continue;
const i = part.indexOf('=');
if (i < 0) out.push([part, '']);
else out.push([part.slice(0, i), part.slice(i + 1)]);
}
return out;
}
export function canonQuery(url) {
const u = new URL(url);
const raw = u.search.startsWith('?') ? u.search.slice(1) : '';
const ps = parsePairs(raw).map(([k, v]) => [feQuery(decComponent(k)), feQuery(decComponent(v))]);
ps.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0));
return { pathname: u.pathname, query: ps.map(([k, v]) => k + '=' + v).join('&') };
}
// 表单对象的 value 编码,和 query 的 fe 不是同一套
function formEncode(data) {
const parts = [];
for (const k of Object.keys(data)) {
const v = data[k];
parts.push(encodeURIComponent(k) + '=' + encodeURIComponent(v == null ? '' : String(v)));
}
return parts.join('&');
}
export function canonBody(method, data, contentType) {
const m = String(method || 'POST').toUpperCase();
if (m === 'GET' || m === 'HEAD') return '';
if (data === undefined || data === null) return '';
let body;
if (typeof data === 'string') body = data;
else {
const ct = String(contentType || '').toLowerCase();
body = ct.includes('json') ? JSON.stringify(data) : formEncode(data);
}
return body.length > BODY_LIMIT ? body.slice(0, BODY_LIMIT) : body;
}
export function buildZ({ method, url, data, contentType }) {
const m = String(method || 'POST').toUpperCase();
const q = canonQuery(url);
const head = m + ' ' + q.pathname + ' ' + q.query;
return Buffer.concat([u8(head), u8(canonBody(m, data, contentType))]);
}
export const buildX = (z, a2) => murmur3(z, a2) >>> 0;
// a5 里的 `_`:对 a5 字符串本身取 murmur3
export const buildUnderscore = (a5, a2) => murmur3(u8(a5), a2) >>> 0;
// a4 = hex( BE32(x) ‖ BE32(_) ‖ LE32(x) ‖ LE32(_) ‖ LE32(x^s32) ‖ LE32(x^_^s32) )
export function buildA4(x, under, a2) {
const s32 = a2 >>> 0;
return Buffer.concat([be4(x), be4(under), le4(x), le4(under), le4(x ^ s32), le4(x ^ under ^ s32)]).toString('hex');
}
// d1 = hexLE( B ),B 由 md5(M) 的 4 个 int 经异或混淆得到
export function buildD1({ a1, a2, a3, a4, under, a6, a7, x0 = 3 }) {
const s32 = a2 >>> 0;
const v = md5hex(Buffer.concat([u8(a6), be4(s32)]));
const M = String(a1) + String(a2) + String(a3) + String(a4) + String(under) + v + String(a7);
const B = md5ints(u8(M));
const u = under >>> 0, f = u;
const j = ((s32 << x0) | (s32 << (32 - x0))) >>> 0;
B[0] = (B[0] ^ j) >>> 0; B[1] = (B[1] ^ f) >>> 0; B[2] = (B[2] ^ f ^ j) >>> 0; B[3] = (B[3] ^ B[0]) >>> 0;
return hexInts(B);
}
// ---------------- 主入口 ----------------
// identity: { appid, dfpid, a6, a2 } —— a6/a2 可与 a5 复用;runtime: { route, openId, appVersion, switchState, loc, initSec, seq, r }
export function sign({ method = 'POST', url, data = '', contentType, identity, runtime, seq, initSec }) {
const a2 = identity.a2 || Date.now();
const a6 = identity.a6;
// 未传 r 时默认 1 易错;出签应传 runtime.r(从旧 mtgsig 反算)
const r = runtime.r === undefined ? 1 : runtime.r;
const qn = buildQn({
appid: identity.appid, openId: runtime.openId, route: runtime.route,
appVersion: runtime.appVersion, envVersion: runtime.envVersion, loc: runtime.loc, switchState: runtime.switchState,
initSec: initSec || Math.floor(a2 / 1000), seq: seq || 1, failReports: runtime.failReports,
});
const a5 = buildA5(a6, a2, qn, r);
const x = buildX(buildZ({ method, url, data, contentType }), a2);
const under = buildUnderscore(a5, a2);
const a1 = '1.2';
const a4 = buildA4(x, under, a2);
const d1 = buildD1({ a1, a2, a3: identity.dfpid, a4, under, a6, a7: identity.appid });
return JSON.stringify({ a1, a2, a3: identity.dfpid, a4, a5, a6, a7: identity.appid, x0: 3, d1 });
}
export { be4, le4, u8, md5ints, hexInts };
@@ -0,0 +1,387 @@
// mtgsig 出签服务(常驻):小程序 jsguard(纯算/补环境)+ 外卖 H5guard
// 启动: node serve.mjs 端口默认 18092(MTGSIG_PORT 可改)
// 接口: GET /health -> {ok,ready,h5Profiles,port,uptimeSec}
// POST /sign {url,data,mtgsig,openId,method,mode,sys?,ext?} 小程序签名(sys/ext 按字段名覆盖 a6 的 system/ext,仅纯算生效)
// POST /sign_h5 {url,data,method,mode,type,dataType,profile,cookie?} 外卖/买药 H5 签名(H5guard 补环境;profile=设备环境,缺字段报错)
// POST /sign_h5_pure {url,data,mtgsig,method,origin_url?,origin_data?} H5(h1.9) 纯算出签(不跑 SDK,毫秒级)
// POST /derive {mtgsig} 解出小程序签名身份
import http from 'node:http';
import crypto from 'node:crypto';
import zlib from 'node:zlib';
import fs from 'node:fs';
import path from 'node:path';
import vm from 'node:vm';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { createSigner } from './signer.mjs';
import * as P from './pure.mjs';
import { buildEnv as buildH5Env, setScriptRunner as setH5ScriptRunner } from './h5-env.mjs';
// H5(h1.9) 纯算(不加载 H5guard):从一份 mtgsig 推会话,再按 url+body 出签
const H5P = await import(pathToFileURL('C:/Users/mjz/Desktop/python/mjz/测试/AI代码/mtgsig_js/h5-pure.mjs').href);
// a6 = "w1.6" + base64(AES-128-CBC(gzip(身份数组))),key/iv 在已测 w1.6 样本上与 jsguard 一致(其它版本需再验)
const A6_KEY = Buffer.from('z7Jut6Ywr2Pe5Nhx');
const A6_IV = Buffer.from('0807060504030201');
// a5 = 自定义base64( y(16B) ‖ RC4_y(JSON.stringify(qn)) ),qn 是本次请求的上下文
const A5_ALPHA = 'ZmserbBoHQtNP+wOcza/LpngG8yJq42KWYj0DSfdikx3VT16IlUAFM97hECvuRX5';
function b64alpha(s) {
let buf = 0, nb = 0;
const out = [];
for (const ch of s) {
const v = A5_ALPHA.indexOf(ch);
if (v < 0) continue;
buf = (buf << 6) | v;
nb += 6;
if (nb >= 8) { nb -= 8; out.push((buf >> nb) & 0xff); }
}
return Buffer.from(out);
}
// 与 jsguard 一致的 RC4 变体(KSA 里多加了 +31)
function rc4Twist(key, data) {
const S = [];
for (let i = 0; i < 256; i++) S[i] = i;
let j = 0;
for (let i = 0; i < 256; i++) { j = (j + S[i] + key[i % key.length] + 31) % 256; const t = S[i]; S[i] = S[j]; S[j] = t; }
const out = Buffer.alloc(data.length);
let i = 0; j = 0;
for (let k = 0; k < data.length; k++) {
i = (i + 1) % 256; j = (j + S[i]) % 256;
const t = S[i]; S[i] = S[j]; S[j] = t;
out[k] = data[k] ^ S[(S[i] + S[j]) % 256];
}
return out;
}
// 从一份 mtgsig(最好是抓包里的旧签名)解出会话身份 + 请求上下文
function deriveFromMtgsig(mtgsig) {
const p = typeof mtgsig === 'string' ? JSON.parse(mtgsig) : mtgsig;
const buf = Buffer.from(String(p.a6).slice(P.a6PrefixOf(p.a6).length), 'base64');
const d = crypto.createDecipheriv('aes-128-cbc', A6_KEY, A6_IV);
const arr = JSON.parse(zlib.gunzipSync(Buffer.concat([d.update(buf), d.final()])).toString('utf8'));
const out = { appid: arr[0], dfpid: p.a3, localId: arr[4], filetime: arr[2], fpv: arr[3], sys: arr[5], ext: arr[7], sessionId: arr[8], a6Prefix: P.a6PrefixOf(p.a6) };
try {
// a6 的 system 数组里带着真机的启动页路径(LaunchOptionsSync),直接复用
const lp = (arr[5] || []).find((v) => typeof v === 'string' && v.startsWith('{"path"'));
if (lp) out.launchPath = JSON.parse(lp).path;
} catch (e) {}
try {
const w = b64alpha(String(p.a5));
const qn = JSON.parse(rc4Twist(w.slice(0, 16), w.slice(16)).toString('utf8'));
out.route = qn.b2 || '';
out.switchState = qn.b9 || '';
out.loc = qn.b11 || '';
out.openId = qn.b6 || '';
out.appVersion = (qn.b1 && qn.b1.miniProgram && qn.b1.miniProgram.version) || '';
out.envVersion = (qn.b1 && qn.b1.miniProgram && qn.b1.miniProgram.envVersion) || '';
if (Array.isArray(qn.b10) && qn.b10.length) out.failReports = qn.b10;
// 防篡改位图 r 同样能从包里反算:y[7] = r ^ crc32(BE32(a2低32))
const y = w.slice(0, 16);
out.r = y[7] ^ (P.crc32(P.be4(p.a2 >>> 0)) & 255);
} catch (e) { /* 旧签名拿不到上下文就算了 */ }
return out;
}
// a6 里 system 数组的 46 项顺序(= jsguard vt.system),按字段名覆盖时靠它映射到下标
const SYSTEM_FIELDS = [
'accelerometer', 'albumAuthorized', 'BatteryInfo', 'batteryLevel', 'Beacons', 'benchmarkLevel',
'bluetoothEnabled', 'brand', 'brightness', 'cameraAuthorized', 'compass', 'deviceOrientation',
'devicePixelRatio', 'enableDebug', 'errMsg', 'fontSizeSetting', 'language', 'LaunchOptionsSync',
'locationAuthorized', 'locationEnabled', 'locationReducedAccuracy', 'microphoneAuthorized', 'model',
'networkType', 'notificationAlertAuthorized', 'notificationAuthorized', 'notificationBadgeAuthorized',
'notificationSoundAuthorized', 'pixelRatio', 'platform', 'safeArea', 'screenHeight', 'screenTop',
'screenWidth', 'SDKVersion', 'statusBarHeight', 'system', 'version', 'wifiEnabled', 'WifiInfo',
'windowHeight', 'windowWidth', 'screenRecord', 'isPrivacy', 'hasSystemProxy', 'captureRecord',
];
// a6 里 ext 数组的 5 项
const EXT_FIELDS = ['NativeClient', 'addEventListener', 'getPublicLibVersion', '__WeixinJSBridge', 'NFC'];
// 按字段名把 override 覆盖到 base 数组(override 不传/空 = 原样返回;字段名不在清单里直接报错)
function applyNamed(base, order, override, label) {
if (!override) return base;
const out = Array.isArray(base) ? base.slice() : [];
for (const k of Object.keys(override)) {
const i = order.indexOf(k);
if (i < 0) throw new Error('未知的 ' + label + ' 字段: ' + k + '(可用字段: ' + order.join(', ') + ')');
out[i] = override[k];
}
return out;
}
const PORT = Number(process.env.MTGSIG_PORT || 18092);
const HOST = '0.0.0.0';
// 每个 (appid|dfpid) 一个出签实例(含 jsguard init 与 dfp 登记),首次调用会等几秒
const cache = new Map();
const startedAt = Date.now();
async function getSigner(id, openId) {
const key = id.appid + '|' + id.dfpid;
if (cache.has(key)) return cache.get(key);
const p = createSigner({
appid: id.appid,
openId: openId || '',
mtime: Number(id.filetime),
route: id.route || '',
launchPath: id.launchPath || '',
appVersion: id.appVersion || '',
loc: id.loc || '',
switchState: id.switchState || '',
sessionId: id.sessionId || '',
sys: id.sys,
ext: id.ext,
seedDfp: { dfpId: String(id.dfpid), localId: String(id.localId), timestamp: Number(id.filetime) },
});
cache.set(key, p);
try { return await p; } catch (e) { cache.delete(key); throw e; }
}
function readBody(req) {
return new Promise((resolve) => {
let b = '';
req.on('data', (c) => (b += c));
req.on('end', () => resolve(b));
});
}
async function handleSign(o) {
if (!o.url) throw new Error('缺 url');
if (o.data === undefined) throw new Error('缺 data');
if (!o.mtgsig) throw new Error('缺 mtgsig(用它解出 appid/dfpid/localId/filetime)');
const id = deriveFromMtgsig(o.mtgsig);
const openId = o.openId || id.openId;
if (!openId) throw new Error('缺 openId(a6 里要带账号身份;旧 mtgsig 的 qn.b6 有的话也能自动取)');
const data = o.data == null ? '' : o.data;
const method = (o.method || 'POST').toUpperCase();
// 字符串看首字符;对象没标 type 时按表单(和 get_mtgsig 的字典约定一致)。显式 contentType 优先
const contentType = o.contentType || (typeof data === 'string' && /^\s*[{[]/.test(data) ? 'application/json' : 'application/x-www-form-urlencoded');
// 默认走纯算(无 init、无预热);要旧的补环境路径就显式传 mode: 'bundle'
const mode = String(o.mode || 'pure').toLowerCase();
if (mode === 'pure') {
const mtgsig = signPure(id, openId, { url: o.url, data, method, contentType, sys: o.sys, ext: o.ext, r: o.r });
const p = JSON.parse(mtgsig);
return { mtgsig, mode, a3: p.a3, appid: id.appid, a5len: p.a5.length, a6len: p.a6.length };
}
const s = await getSigner(id, openId);
const mtgsig = s.sign({ url: o.url, data, method, contentType });
const p = JSON.parse(mtgsig);
return { mtgsig, mode: 'bundle', a3: p.a3, appid: id.appid, a5len: p.a5.length, a6len: p.a6.length };
}
// 纯算模式:不加载 jsguard、不 init,因此没有那 20s 预热,换新包即出即用
const pureState = new Map(); // appid|dfpid -> { seq, initSec }
function signPure(id, openId, { url, data, method, contentType, sys, ext, r }) {
const key = id.appid + '|' + id.dfpid;
let st = pureState.get(key);
if (!st) { st = { seq: 1, initSec: Math.floor(Date.now() / 1000) }; pureState.set(key, st); } else st.seq += 1;
// 防篡改位图:优先调用方 r,否则用旧包 a5 反算 id.r;仅都无时才回退 1(真机常见为 0,回退 1 可能错签)
const bitmapR = r === undefined || r === null ? (id.r === undefined ? 1 : id.r) : Number(r);
const a2 = Date.now();
const a6 = P.buildA6FromParts({
appid: id.appid, dfpid: id.dfpid, filetime: id.filetime, fpv: id.fpv || '2.5.0',
localid: id.localId, sessionId: id.sessionId, a6Prefix: id.a6Prefix,
sys: applyNamed(id.sys, SYSTEM_FIELDS, sys, 'system'),
ext: applyNamed(id.ext, EXT_FIELDS, ext, 'ext'),
timestamp: Math.ceil(a2 / 1000),
});
return P.sign({
method, url, data, contentType,
identity: { appid: id.appid, dfpid: id.dfpid, a6, a2 },
runtime: { openId, route: id.route, appVersion: id.appVersion, envVersion: id.envVersion, loc: id.loc, switchState: id.switchState, failReports: id.failReports, r: bitmapR },
initSec: st.initSec, seq: st.seq,
});
}
// ---------- H5guard(外卖/买药 H5,浏览器环境 shim) ----------
// 每个 profile(设备/身份)一套独立 vm + H5guard;环境全部由 profile 决定,不再有内置默认身份
const HERE = path.dirname(fileURLToPath(import.meta.url));
const H5_PKG = fs.readFileSync(path.join(HERE, 'package-v1.js'), 'utf8');
const H5_SDK = fs.readFileSync(path.join(HERE, 'H5guard.js'), 'utf8');
const h5Profiles = new Map(); // profileKey -> { env, ready, fpLen }
function h5ProfileKey(p) {
return [p.appid, p.ua, p.platform, p.screenWidth, p.screenHeight, p.devicePixelRatio].join('|');
}
function getH5Profile(profile) {
if (!profile || !profile.appid || !profile.domains) throw new Error('profile 缺 appid 或 domains');
const key = h5ProfileKey(profile);
let st = h5Profiles.get(key);
if (st) return st;
const env = buildH5Env(profile);
const ctx = vm.createContext(env);
setH5ScriptRunner((code, name) => vm.runInContext(code, ctx, { filename: name }));
vm.runInContext(H5_PKG, ctx, { filename: 'package-v1.js' });
vm.runInContext(H5_SDK, ctx, { filename: 'H5guard.js' });
st = { key, env, ready: false, fpLen: 0 };
h5Profiles.set(key, st);
try { env.H5guard.init({ appid: profile.appid, xhrHook: true, domains: profile.domains, geo: false, yodaEnv: undefined }); } catch (e) { /* 已发起后台初始化 */ }
const t0 = Date.now(); let last = -1; let stable = 0;
const iv = setInterval(() => {
let len = -1;
try { len = String(env.H5guard.getfp()).length; } catch (e) { len = -1; }
if (len > 0 && len === last) stable++; else stable = 0;
last = len;
const el = Date.now() - t0;
if ((el >= 3500 && stable >= 2) || el >= 20000) {
clearInterval(iv);
st.fpLen = Math.max(0, len);
st.ready = true;
console.log('H5 READY[' + key + '] fpLen=' + st.fpLen + ' 预热=' + (el / 1000).toFixed(1) + 's');
}
}, 250);
return st;
}
function h5WaitReady(st) {
if (st.ready) return Promise.resolve();
return new Promise((res) => { const iv = setInterval(() => { if (st.ready) { clearInterval(iv); res(); } }, 200); });
}
let h5Queue = Promise.resolve(); // 串行化,避免并发互相干扰 SDK 状态
// 路径一:手动 H5guard.sign() -> a6 前缀 h1.9(外卖/买药 H5 页面自身加签走的这条)
function signH5Api(o, st) {
return (async () => {
const env = st.env;
if (o.cookie !== undefined) env.document.cookie = String(o.cookie || '');
const t = await env.H5guard.sign({
cache: false,
dataType: o.dataType,
url: o.url,
type: String(o.type).toUpperCase(),
data: o.data,
method: String(o.method).toUpperCase(),
});
return { mtgsig: t.headers.mtgsig, url: o.url, headers: {}, mode: 'sign' };
})();
}
// 路径二:走 H5guard 自己装的 XHR 钩子(signType 2)-> a6 前缀 hs1.6
// 白名单域名来自 init 的 domains(profile.domains):GET 把 mtgsig 拼进 url、POST 塞 header
function signH5Xhr(o, st) {
return new Promise((resolve, reject) => {
try {
const env = st.env;
if (o.cookie !== undefined) env.document.cookie = String(o.cookie || '');
const method = String(o.method).toUpperCase();
const xhr = new env.XMLHttpRequest();
xhr.open(method, o.url, true);
if (o.contentType) xhr.setRequestHeader('content-type', o.contentType);
if (o.headers) for (const k of Object.keys(o.headers)) xhr.setRequestHeader(k, o.headers[k]);
xhr.send(o.data);
const t0 = Date.now();
const iv = setInterval(() => {
const g = xhr.guardReq || {};
const u = String(g.url || '');
const hs = g.headers || {};
let mtgsig = null;
const m = u.match(/mtgsig=([^&]+)/);
if (m) mtgsig = decodeURIComponent(m[1]);
else if (hs.mtgsig) mtgsig = String(hs.mtgsig);
if (mtgsig) { clearInterval(iv); resolve({ mtgsig, url: u || o.url, headers: hs, mode: 'xhr' }); return; }
if (Date.now() - t0 > 15000) { clearInterval(iv); reject(new Error('H5 XHR 出签超时(域名可能不在 domains 白名单,或请求没被 SDK 钩到)')); }
}, 50);
} catch (e) { reject(e); }
});
}
function signH5(o, st) {
const mode = String(o.mode).toLowerCase();
if (mode !== 'sign' && mode !== 'xhr') throw new Error('mode 非法(只能 sign 或 xhr): ' + JSON.stringify(o.mode));
const run = h5Queue.then(() => (mode === 'sign' ? signH5Api(o, st) : signH5Xhr(o, st)));
h5Queue = run.then(() => {}, () => {}); // 单次失败不毒化后续请求
return run;
}
// H5(h1.9) 纯算:用一份抓包 mtgsig 推会话(origin_url/origin_data 要和那份包一致,默认同 url/data),
// 再按新 url/data 出签;同一个 dfpid(a3) 的 seq 自增(qn[2] 服务端会核对)
const h5PureSeq = new Map(); // a3(dfpid) -> seq
function signH5Pure(o) {
const data = o.data || '';
const method = (o.method || 'POST').toUpperCase();
const mtg = typeof o.mtgsig === 'string' ? JSON.parse(o.mtgsig) : o.mtgsig;
const snap = H5P.deriveFromMtgsig(mtg, {
url: o.origin_url || o.url,
data: o.origin_data === undefined ? data : o.origin_data,
method,
});
const key = String(mtg.a3);
const seq = h5PureSeq.has(key) ? h5PureSeq.get(key) + 1 : snap.seq + 1;
h5PureSeq.set(key, seq);
const a2 = o.a2 || Date.now();
const sig = H5P.sign(snap, { url: o.url, data, method, a2, seq });
return { mtgsig: JSON.stringify(sig), D: snap.D, seq };
}
const server = http.createServer(async (req, res) => {
const u = new URL(req.url, 'http://' + HOST);
const send = (code, obj) => { res.writeHead(code, { 'content-type': 'application/json; charset=utf-8' }); res.end(JSON.stringify(obj)); };
try {
if (req.method === 'GET' && u.pathname === '/health') {
return send(200, { ok: true, port: PORT, uptimeSec: Math.round((Date.now() - startedAt) / 1000), ready: true, h5Profiles: [...h5Profiles.values()].map((s) => ({ key: s.key, ready: s.ready, fpLen: s.fpLen })), identities: [...cache.keys()] });
}
if (u.pathname === '/sign_h5') {
let o = {};
if (req.method === 'POST') {
const raw = await readBody(req);
o = raw ? JSON.parse(raw) : {};
} else {
o = Object.fromEntries(u.searchParams.entries());
}
for (const k of ['url', 'data', 'method', 'mode', 'type', 'dataType', 'profile']) {
if (o[k] === undefined) return send(400, { error: '缺 ' + k });
}
const st = getH5Profile(o.profile); // 按 profile 建/取一套环境(profile 缺字段会报错)
await h5WaitReady(st); // 该 profile 首次会等指纹预热(最多 20s)
const r = await signH5(o, st);
const m = JSON.parse(r.mtgsig);
return send(200, { mtgsig: r.mtgsig, url: r.url, headers: r.headers, mode: r.mode, a3: m.a3, a6pfx: String(m.a6).slice(0, 5) });
}
if (u.pathname === '/sign_h5_pure') {
let o = {};
if (req.method === 'POST') {
const raw = await readBody(req);
o = raw ? JSON.parse(raw) : {};
} else {
o = Object.fromEntries(u.searchParams.entries());
}
if (!o.url) return send(400, { error: '缺 url' });
if (!o.mtgsig) return send(400, { error: '缺 mtgsig(用它推会话:a5 的 qn / a8 的 A / d1 的 pool2)' });
const r = signH5Pure(o);
const m = JSON.parse(r.mtgsig);
return send(200, { mtgsig: r.mtgsig, mode: 'h5-pure', a3: m.a3, a6pfx: String(m.a6).slice(0, 5), D: r.D, seq: r.seq });
}
if (u.pathname === '/derive') {
let mtgsig;
if (req.method === 'POST') { const raw = await readBody(req); mtgsig = (raw ? JSON.parse(raw) : {}).mtgsig; }
else mtgsig = u.searchParams.get('mtgsig') || '';
return send(200, deriveFromMtgsig(mtgsig));
}
if (u.pathname === '/sign') {
let o = {};
if (req.method === 'POST') {
const raw = await readBody(req);
o = raw ? JSON.parse(raw) : {};
} else {
o = Object.fromEntries(u.searchParams.entries());
}
const r = await handleSign(o);
return send(200, r);
}
send(404, { error: 'not found' });
} catch (e) {
send(500, { error: e && (e.message || String(e)) });
}
});
server.on('error', (e) => {
if (e && e.code === 'EADDRINUSE') { console.error('端口 ' + PORT + ' 已被占用,先停掉旧服务或改 MTGSIG_PORT'); process.exit(1); }
console.error(e);
process.exit(1);
});
server.listen(PORT, HOST, () => {
console.log('mtgsig 出签服务已启动: http://' + HOST + ':' + PORT + ' (health: /health)');
});
@@ -0,0 +1,366 @@
// wx-jsguard 本地出签器:在 Node 的 vm 上下文里补 wx 环境跑美团小程序 jsguard,产出 mtgsig
// 纯本地,不依赖小程序运行时、不依赖远端签名服务(SDK 自身会走 msp.meituan.com 的指纹登记)
import fs from 'node:fs';
import path from 'node:path';
import vm from 'node:vm';
import { fileURLToPath } from 'node:url';
// 每个小程序必须有自己的签名 SDK:jsguard-<appid>.js(用 提取jsguard.py 生成),不做降级
const HERE = path.dirname(fileURLToPath(import.meta.url));
export function resolveSdk(appid) {
if (process.env.WR_SDK) return process.env.WR_SDK;
if (appid) {
const p = path.join(HERE, 'jsguard-' + appid + '.js');
if (fs.existsSync(p)) return p;
}
const have = fs.readdirSync(HERE).filter((f) => /^jsguard-.+\.js$/.test(f)).map((f) => f.slice(8, -3));
throw new Error('未适配该小程序(appid=' + (appid || '未知') + ')。已适配: ' + (have.join(', ') || '无') +
';先跑 `python 提取jsguard.py ' + (appid || '<appid>') + '`');
}
// a5 = 自定义base64( y(16B) ‖ RC4_y(JSON.stringify(qn)) ),用来读回本次请求的上下文
const A5_ALPHA = 'ZmserbBoHQtNP+wOcza/LpngG8yJq42KWYj0DSfdikx3VT16IlUAFM97hECvuRX5';
export function b64alpha(s) {
let buf = 0, nb = 0;
const out = [];
for (const ch of s) {
const v = A5_ALPHA.indexOf(ch);
if (v < 0) continue;
buf = (buf << 6) | v;
nb += 6;
if (nb >= 8) { nb -= 8; out.push((buf >> nb) & 0xff); }
}
return Buffer.from(out);
}
// 与 jsguard 一致的 RC4 变体(KSA 多加 +31)
export function rc4Twist(key, data) {
const S = [];
for (let i = 0; i < 256; i++) S[i] = i;
let j = 0;
for (let i = 0; i < 256; i++) { j = (j + S[i] + key[i % key.length] + 31) % 256; const t = S[i]; S[i] = S[j]; S[j] = t; }
const out = Buffer.alloc(data.length);
let i = 0; j = 0;
for (let k = 0; k < data.length; k++) {
i = (i + 1) % 256; j = (j + S[i]) % 256;
const t = S[i]; S[i] = S[j]; S[j] = t;
out[k] = data[k] ^ S[(S[i] + S[j]) % 256];
}
return out;
}
// 解出 a5 里带的 qn(请求上下文:路由/开关位/定位精度等)
export function decodeQn(a5) {
const w = b64alpha(String(a5));
return JSON.parse(rc4Twist(w.slice(0, 16), w.slice(16)).toString('utf8'));
}
const LOG = process.env.WR_LOG === '1';
const SYSTEM_INFO = {
brand: 'microsoft', model: 'microsoft', system: 'Windows 10 x64', platform: 'windows',
version: '4.1.12.24', SDKVersion: '3.17.3', language: 'zh_CN',
screenWidth: 414, screenHeight: 780, windowWidth: 414, windowHeight: 780,
pixelRatio: 1, devicePixelRatio: 1, statusBarHeight: 20,
benchmarkLevel: -1, bluetoothEnabled: false, wifiEnabled: true, locationEnabled: true,
enableDebug: false, errMsg: 'getSystemInfo:ok',
safeArea: { left: 0, right: 414, top: 0, bottom: 780, width: 414, height: 780 },
};
// 从旧 mtgsig 的 a6 system 数组还原真机设备画像(字段顺序 = jsguard 的 DFP 顺序)
function deviceFromSys(S) {
if (!Array.isArray(S) || S.length < 45) return null;
const at = (i, d) => (S[i] === undefined || S[i] === null ? d : S[i]);
const opt = (i, k, o) => (at(i, null) === null ? o : { ...o, [k]: at(i) });
let lo = {};
try { lo = JSON.parse(at(17, '{}')); } catch (e) {}
const sa = Array.isArray(at(30, null)) ? at(30) : null;
const bi = Array.isArray(at(2, null)) ? at(2) : null;
let sys = {
brand: at(7, 'microsoft'), model: at(22, 'microsoft'), system: at(36, 'Windows 10 x64'), platform: at(29, 'windows'),
version: at(37, '10.38.3'), SDKVersion: at(34, '3.17.3'), language: at(16, 'zh_CN'),
fontSizeSetting: at(15, undefined), screenWidth: at(33, 414), screenHeight: at(31, 780),
windowWidth: at(41, 414), windowHeight: at(40, 780), pixelRatio: at(28, 1), devicePixelRatio: at(12, 1),
statusBarHeight: at(35, 20), benchmarkLevel: at(5, -1), bluetoothEnabled: at(6, false),
wifiEnabled: at(38, true), locationEnabled: at(19, true), enableDebug: at(13, false),
errMsg: at(14, 'getSystemInfo:ok'),
};
sys = opt(11, 'deviceOrientation', sys);
sys = opt(32, 'screenTop', sys);
sys = opt(1, 'albumAuthorized', sys);
sys = opt(9, 'cameraAuthorized', sys);
sys = opt(18, 'locationAuthorized', sys);
sys = opt(21, 'microphoneAuthorized', sys);
sys = opt(25, 'notificationAuthorized', sys);
sys = opt(20, 'locationReducedAccuracy', sys);
if (sa) sys.safeArea = { left: sa[0], right: sa[1], top: sa[2], bottom: sa[3], width: sa[4], height: sa[5] };
return {
sys,
launchOptions: { path: lo.path || 'pages/index/index', scene: lo.scene === undefined ? 1256 : lo.scene, query: {}, referrerInfo: {}, isSticky: false },
networkType: at(23, 'wifi'),
hasSystemProxy: at(44, -1),
brightness: at(8, 0.5),
battery: bi ? { errMsg: bi[0] || 'getBatteryInfo:ok', isCharging: !!bi[1], level: bi[2] } : { errMsg: 'getBatteryInfo:ok', isCharging: true, level: 100 },
beaconsOk: typeof at(4, null) === 'string',
};
}
const SUCCESS = (o) => ({ errMsg: 'ok', ...o });
// 真机 USER_DATA_PATH 目录的 lastModifiedTime(毫秒),影响 a6 里的 filetime/localid
const FILE_MTIME = Number(process.env.WR_MTIME || 1787118064811);
const STORE = new Map();
function buildWx(log, cfg) {
const appid = cfg.appid;
const D = cfg.sys ? deviceFromSys(cfg.sys) : null;
const SI = D ? D.sys : SYSTEM_INFO;
const appVersion = cfg.appVersion || SI.version;
const launchPath = cfg.launchPath || (D ? D.launchOptions.path : 'pages/index/index');
const mtime = cfg.mtime || FILE_MTIME;
const track = cfg.track; // 统计 et 上报(ops.meituan.com)在途/完成
const mk = (name, impl) => function (...a) {
log.push(name);
if (LOG) console.error('[wx] ' + name + '(' + a.map((x) => (typeof x === 'function' ? 'fn' : JSON.stringify(x))).join(', ') + ')');
if (impl) return impl.apply(this, a);
};
return {
getSystemInfoSync: mk('getSystemInfoSync', () => SI),
getSystemInfo: mk('getSystemInfo', (o) => { if (o && o.success) o.success(SUCCESS(SI)); if (o && o.complete) o.complete(SUCCESS(SI)); }),
getDeviceInfo: mk('getDeviceInfo', () => SI),
getWindowInfo: mk('getWindowInfo', () => ({ pixelRatio: SI.pixelRatio, screenWidth: SI.screenWidth, screenHeight: SI.screenHeight, windowWidth: SI.windowWidth, windowHeight: SI.windowHeight, statusBarHeight: SI.statusBarHeight, safeArea: SI.safeArea })),
getAppBaseInfo: mk('getAppBaseInfo', () => ({ SDKVersion: SI.SDKVersion, language: SI.language, version: appVersion, platform: SI.platform, theme: 'light', enableDebug: SI.enableDebug })),
getAppAuthorizeSetting: mk('getAppAuthorizeSetting', () => ({ albumAuthorized: 'authorized', cameraAuthorized: 'authorized', locationAuthorized: 'authorized', microphoneAuthorized: 'authorized', notificationAuthorized: 'authorized' })),
getSetting: mk('getSetting', (o) => { if (o && o.success) o.success(SUCCESS({ authSetting: {}, subscriptionsSetting: {} })); }),
getPublicLibVersion: mk('getPublicLibVersion', () => (cfg.ext && cfg.ext[2] === 1 ? { system: SI.platform } : {})),
getNetworkType: mk('getNetworkType', (o) => { if (o && o.success) o.success(SUCCESS({ networkType: D ? D.networkType : 'wifi', hasSystemProxy: D ? D.hasSystemProxy === 1 : false })); }),
getScreenBrightness: mk('getScreenBrightness', (o) => { if (o && o.success) o.success(SUCCESS({ value: D ? D.brightness : 0.5 })); }),
getBatteryInfoSync: mk('getBatteryInfoSync', () => (D ? D.battery : { errMsg: 'getBatteryInfo:ok', level: 100, isCharging: true })),
getBatteryInfo: mk('getBatteryInfo', (o) => { const r = D ? D.battery : { errMsg: 'getBatteryInfo:ok', level: 100, isCharging: true }; if (o && o.success) o.success(r); if (o && o.complete) o.complete(r); }),
getScreenRecordingState: mk('getScreenRecordingState', (o) => { if (o && o.fail) o.fail({ errMsg: 'getScreenRecordingState:fail' }); if (o && o.complete) o.complete({ errMsg: 'getScreenRecordingState:fail' }); }),
getLocalIPAddress: mk('getLocalIPAddress', (o) => { if (o && o.success) o.success(SUCCESS({ localip: '192.168.1.100' })); }),
getStorageInfo: mk('getStorageInfo', (o) => { if (o && o.success) o.success(SUCCESS({ keys: ['a'], currentSize: 1, limitSize: 10240 })); }),
getStorageInfoSync: mk('getStorageInfoSync', () => ({ keys: ['a'], currentSize: 1, limitSize: 10240 })),
getStorageSync: mk('getStorageSync', (k) => {
if (cfg.seedDfp && k === '40a10de2') return { id: { ...cfg.seedDfp } };
return STORE.has(k) ? STORE.get(k) : '';
}),
setStorageSync: mk('setStorageSync', (k, v) => { STORE.set(k, v); }),
setStorage: mk('setStorage', (o) => { if (o && o.key !== undefined) STORE.set(o.key, o.data); if (o && o.success) o.success({ errMsg: 'setStorage:ok' }); }),
getBeacons: mk('getBeacons', (o) => {
if (D && D.beaconsOk) { if (o && o.success) o.success(SUCCESS({ beacons: [] })); return; }
if (o && o.fail) o.fail({ errMsg: 'getBeacons:fail' }); if (o && o.complete) o.complete({ errMsg: 'getBeacons:fail' });
}),
getSelectedTextRange: mk('getSelectedTextRange', (o) => { if (o && o.success) o.success(SUCCESS({ start: 0, end: 0 })); }),
getLaunchOptionsSync: mk('getLaunchOptionsSync', () => (D ? D.launchOptions : { path: launchPath, scene: 1256, query: {}, referrerInfo: {}, isSticky: false })),
getLocation: mk('getLocation', (o) => { if (o && o.success) o.success(SUCCESS({ latitude: 23.129, longitude: 113.264, accuracy: 65, horizontalAccuracy: 65, verticalAccuracy: 65 })); }),
startWifi: mk('startWifi', (o) => { if (o && o.success) o.success(SUCCESS({})); }),
getConnectedWifi: mk('getConnectedWifi', (o) => { if (o && o.error) o.error({ errMsg: 'not connected' }); }),
getWifiList: mk('getWifiList', () => undefined),
onGetWifiList: mk('onGetWifiList', () => undefined),
// NFC 一项影响指纹里的 ext 数组:真机 Android 有 NFC 且 startDiscovery 失败(=0),Windows 无该 API(=4)
canIUse: mk('canIUse', (n) => !(n === 'getNFCAdapter' && (cfg.ext ? cfg.ext[4] : 4) === 4)),
getNFCAdapter: mk('getNFCAdapter', () => {
const nfc = cfg.ext ? cfg.ext[4] : 4;
return {
startDiscovery: (o) => { if (nfc === 1) { if (o && o.success) o.success({}); } else if (o && o.fail) o.fail({ errCode: nfc === 3 ? 13000 : nfc === 2 ? 13001 : 0 }); },
stopDiscovery: (o) => { if (o && o.success) o.success({}); },
};
}),
getPrivacySetting: mk('getPrivacySetting', (o) => { if (o && o.success) o.success(SUCCESS({ needAuthorization: false, privacyContractName: '《小程序隐私保护指引》' })); }),
getAccountInfoSync: mk('getAccountInfoSync', () => ({ miniProgram: { appId: appid, envVersion: 'release', version: appVersion } })),
getUserCryptoManager: mk('getUserCryptoManager', () => ({
getLatestUserKey: mk('getLatestUserKey', (o) => {
const k = { encryptKey: '0123456789abcdef', iv: 'abcdef0123456789', version: 1, expireTime: Math.floor(Date.now() / 1000) + 86400 };
if (o && o.success) o.success(SUCCESS(k));
return k;
}),
getRandomValues: mk('getRandomValues', (o) => { if (o && o.success) o.success(SUCCESS({ randomValues: new Uint8Array(16) })); }),
})),
getFileSystemManager: mk('getFileSystemManager', () => ({ statSync: mk('statSync', () => ({ lastModifiedTime: mtime, lastAccessedTime: mtime, size: 4096, mode: 33188, isDirectory: () => true, isFile: () => false })) })),
env: { USER_DATA_PATH: 'wxfile://usr' },
onAppHide: mk('onAppHide', () => undefined),
onAppShow: mk('onAppShow', () => undefined),
onUserCaptureScreen: mk('onUserCaptureScreen', () => undefined),
offUserCaptureScreen: mk('offUserCaptureScreen', () => undefined),
onAccelerometerChange: mk('onAccelerometerChange', () => undefined),
startAccelerometer: mk('startAccelerometer', () => undefined),
onCompassChange: mk('onCompassChange', () => undefined),
startCompass: mk('startCompass', () => undefined),
request: mk('request', (o) => {
let url = o.url;
const method = (o.method || 'GET').toUpperCase();
const headers = o.header || {};
let body;
if (o.data !== undefined) {
if (method === 'GET' || method === 'HEAD') {
const qs = typeof o.data === 'string' ? o.data : Object.entries(o.data).map(([k, v]) => encodeURIComponent(k) + '=' + encodeURIComponent(v)).join('&');
if (qs) url += (url.includes('?') ? '&' : '?') + qs;
} else {
body = typeof o.data === 'string' ? o.data : JSON.stringify(o.data);
}
}
// 微信默认:对象 body -> application/json,字符串 -> x-www-form-urlencoded
const hdrs = { ...headers };
if (!Object.keys(hdrs).some((k) => k.toLowerCase() === 'content-type')) {
hdrs['content-type'] = (o.data !== undefined && typeof o.data !== 'string') ? 'application/json' : 'application/x-www-form-urlencoded';
}
const isEt = url.includes('ops.meituan.com');
if (isEt && track) { track.inFlight++; track.seen = true; }
fetch(url, { method, headers: hdrs, body })
.then(async (r) => {
const text = await r.text();
let data; try { data = JSON.parse(text); } catch (e) { data = text; }
const res = { statusCode: r.status, data, header: Object.fromEntries(r.headers) };
if (LOG) console.error('[net] ' + method + ' ' + url + ' -> ' + r.status + ' ' + text.slice(0, 300));
if (o.success) o.success(res);
if (o.complete) o.complete(res);
if (isEt && track) track.inFlight--;
})
.catch((e) => {
const res = { errMsg: 'request:fail ' + (e && e.message) };
if (LOG) console.error('[net] ' + method + ' ' + url + ' -> FAIL ' + (e && e.message));
if (o.fail) o.fail(res);
if (o.complete) o.complete(res);
if (isEt && track) track.inFlight--;
});
}),
};
}
function patchSdk(src, switchDigits) {
// 被吞掉的出签异常打出来
src = src.replace(
/catch\(e\)\{try\{Qe&&Qe\[c\(39\)\]\(a\(616\),e\)\}catch\(e\)\{\}\}/,
"catch(e){try{console.error('CALCMTGSIG_ERR',e&&(e.stack||e.message||String(e)))}catch(_e){}}"
);
// 开关位串(qn.b9):优先旧 mtgsig 解出的 b9;没有才兜底 22122(五位串随环境变,勿当成固定健康值)
src = src.replace(/(\{su:0,fm:0,fp:0,sig:0\},[A-Za-z_$][\w$]*=)\[0,0,0,0,0\]/, '$1[' + switchDigits.split('').join(',') + ']');
return src;
}
function makeLoader(context, sdkPath, switchDigits) {
const cache = new Map();
const ROOT = path.dirname(sdkPath).replace(/[\\/]npm[\\/].*$/, '');
function load(file) {
const abs = path.resolve(file);
if (cache.has(abs)) return cache.get(abs).exports;
let src = fs.readFileSync(abs, 'utf8');
if (abs === path.resolve(sdkPath)) src = patchSdk(src, switchDigits);
const mod = { exports: {} };
cache.set(abs, mod);
const dir = path.dirname(abs);
const req = (spec) => {
// @babel/runtime/helpers/* 统一从 SDK 所在项目的根目录取
const babel = spec.match(/@babel\/runtime\/helpers\/([\w.-]+)/);
if (babel) return load(path.join(ROOT, '@babel', 'runtime', 'helpers', babel[1] + '.js'));
if (spec.startsWith('.') || path.isAbsolute(spec)) {
let p = path.resolve(dir, spec);
if (!p.endsWith('.js')) { if (fs.existsSync(p + '.js')) p = p + '.js'; else if (fs.existsSync(path.join(p, 'index.js'))) p = path.join(p, 'index.js'); }
return load(p);
}
throw new Error('external require: ' + spec);
};
// 文件名里带 app-service:SDK 的防篡改位图会检查 Error.stack 里是否有 'app-service'/'appservice'
const fn = vm.runInContext('(function(module, exports, require, __filename, __dirname){' + src + '\n})', context, { filename: 'app-service/' + path.basename(abs) });
fn(mod, mod.exports, req, abs, dir);
return mod.exports;
}
return load;
}
export async function createSigner(opts = {}) {
const appid = opts.appid || 'wxde8ac0a21135c07d';
const sdkPath = opts.sdk || resolveSdk(appid);
const calls = [];
// et 上报(ops.meituan.com)在途计数:没落定就出签,qn.b9 会停在中间态 → 判可疑
const track = { inFlight: 0, seen: false };
const sandbox = {
console, setTimeout, clearTimeout, setInterval, clearInterval, queueMicrotask,
fetch, Buffer, TextEncoder, TextDecoder, URL, URLSearchParams, crypto: globalThis.crypto,
wx: buildWx(calls, { appid, appVersion: opts.appVersion, launchPath: opts.launchPath, sys: opts.sys, ext: opts.ext, seedDfp: opts.seedDfp, mtime: opts.mtime, track }),
__wxConfig: { config: { debug: false }, platform: 'windows' },
getCurrentPages: () => (opts.route ? [{ route: opts.route, options: {}, __origin_route__: opts.route }] : []),
navigator: undefined,
};
// ext[1]=addEventListener 是否存在(真机 Android appservice 没有)
if (!opts.ext || opts.ext[1] === 1) sandbox.addEventListener = () => undefined;
sandbox.globalThis = sandbox;
sandbox.self = sandbox;
// appservice 上下文:反篡改位图 r 随环境变(真机 appservice 常见反算 r=0,勿写死为 1)
if (opts.noWindow) { /* 完全不声明 window */ }
else if ('windowValue' in opts) sandbox.window = opts.windowValue;
else sandbox.window = undefined;
sandbox.eval = opts.keepEval ? sandbox.eval : undefined;
if (opts.weixinJSBridge !== false) {
sandbox.WeixinJSBridge = (opts.weixinJSBridge && opts.weixinJSBridge !== true) ? opts.weixinJSBridge : {};
}
sandbox.document = undefined;
// 冻结时间(拿抓包逐字节校验用):让 Date.now()/new Date 返回固定毫秒
if (opts.nowMs) {
const Real = Date;
const FIXED = opts.nowMs;
function FixedDate(...a) { return a.length ? new Real(...a) : new Real(FIXED); }
FixedDate.now = () => FIXED;
FixedDate.parse = Real.parse;
FixedDate.UTC = Real.UTC;
FixedDate.prototype = Real.prototype;
sandbox.Date = FixedDate;
}
const context = vm.createContext(sandbox);
const switchDigits = /^\d{5}$/.test(opts.switchState || '') ? opts.switchState : '22122';
const jsguard = makeLoader(context, sdkPath, switchDigits)(sdkPath);
let inst = null;
const initAt = Date.now();
try {
inst = await Promise.race([
jsguard.init({ appid, env: 'prod' }),
new Promise((_, rej) => setTimeout(() => rej(new Error('init timeout')), opts.initWaitMs || 8000)),
]);
} catch (e) {
inst = jsguard.initSync({ appid, env: 'prod' });
}
const siuaTimer = setInterval(() => { try { inst.finger.i(); } catch (e) {} }, 10000);
// 账号/会话身份要在 SDK 刷新指纹(a6) 之前注入,否则这一轮 a6 里带不上
if (opts.openId) { try { inst.finger.o(opts.openId); } catch (e) {} }
if (opts.unionId) { try { inst.finger.u(opts.unionId); } catch (e) {} }
if (opts.mchId) { try { inst.finger.m(opts.mchId); } catch (e) {} }
if (opts.sessionId) { try { inst.finger.ss(opts.sessionId); } catch (e) {} }
// 定位精度串(qn.b11,形如 "30_30_0"):真机会带,缺了也可疑
if (opts.loc) {
const [acc, hacc, vacc] = String(opts.loc).split('_').map(Number);
try { inst.finger.l({ accuracy: acc, horizontalAccuracy: hacc, verticalAccuracy: vacc }); } catch (e) {}
}
if (opts.settleMs !== 0) {
// SDK 的 a6 每 10s 刷一次;身份注入后必须过一轮才会带进 a6
const need = 10500 - (Date.now() - initAt);
if (need > 0) await new Promise((r) => setTimeout(r, need));
// et 上报也是 10s 周期:等它跑完并静默一段时间,开关位 b9 才回到健康值
const maxMs = opts.settleWaitMs || 30000;
const t0 = Date.now();
let drainedAt = 0;
while (Date.now() - t0 < maxMs) {
await new Promise((r) => setTimeout(r, 500));
if (track.seen && track.inFlight === 0) { if (!drainedAt) drainedAt = Date.now(); }
if (!track.seen && Date.now() - t0 > 8000) break;
if (drainedAt && Date.now() - drainedAt > (opts.settleTailMs || 9000)) break;
}
}
return {
appid,
guard: inst,
calls,
fingerId: () => { try { return inst.finger.i(); } catch (e) { return ''; } },
dfpid: () => { try { return inst.finger.d(); } catch (e) { return ''; } },
sign({ url, method = 'POST', data = '', contentType = 'application/x-www-form-urlencoded' }) {
// content-type 只影响对象 body:json 走 JSON.stringify,表单走插入顺序的 encodeURIComponent。字符串 body 原样进签名串
const req = { url, method, header: { 'content-type': contentType }, data };
const out = inst.signWithSiua(req);
return out.header.mtgsig;
},
close() { clearInterval(siuaTimer); },
};
}
@@ -0,0 +1,90 @@
# 启动 mtgsig 出签常驻服务(幂等:已在跑就不重复起)
import os
import sys
import time
import subprocess
import requests
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
JS_DIR = os.path.join(BASE_DIR, 'mtgsig_js')
PORT = int(os.environ.get('MTGSIG_PORT', 18092))
BASE_URL = 'http://127.0.0.1:%d' % PORT
# BASE_URL = 'http://192.168.1.139:%d' % PORT
LOG_PATH = os.path.join(JS_DIR, 'serve.log')
PROXY = {'http': None, 'https': None}
def is_ready():
try:
r = requests.get(BASE_URL + '/health', timeout=3, proxies=PROXY)
return r.status_code == 200 and r.json().get('ok')
except Exception:
return False
def start():
if is_ready():
print('出签服务已在运行: %s' % BASE_URL)
return
log = open(LOG_PATH, 'a', encoding='utf-8')
flags = 0
if os.name == 'nt':
flags = 0x00000008 | 0x00000200 # DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP
subprocess.Popen(
['node', 'serve.mjs'],
cwd=JS_DIR,
stdout=log,
stderr=log,
creationflags=flags,
)
for _ in range(60):
time.sleep(1)
if is_ready():
print('出签服务已就绪: %s' % BASE_URL)
return
print('等服务起来超时,看日志: %s' % LOG_PATH)
sys.exit(1)
def find_pids_on_port():
"""按端口找出正在监听的进程号(重启用)"""
out = subprocess.run(['netstat', '-ano', '-p', 'tcp'], capture_output=True, text=True).stdout
pids = set()
for line in out.splitlines():
parts = line.split()
if len(parts) >= 5 and parts[1].endswith(':%d' % PORT) and parts[3].upper() == 'LISTENING':
pids.add(parts[4])
return pids
def stop():
"""杀掉监听该端口的出签服务(重启用)"""
pids = find_pids_on_port()
if not pids:
print('出签服务没在运行: %s' % BASE_URL)
return
for pid in pids:
subprocess.run(['taskkill', '/F', '/PID', pid], capture_output=True, text=True)
for _ in range(20):
time.sleep(0.5)
if not find_pids_on_port():
print('出签服务已停止: %s' % BASE_URL)
return
print('停止超时,端口仍被占用: %s' % BASE_URL)
sys.exit(1)
def restart():
"""重启:先杀掉旧的,再重新起一个(改了 serve.mjs 后用这个)"""
stop()
start()
if __name__ == '__main__':
mode = 'restart'
if mode == 'restart':
restart()
elif mode == 'stop':
stop()
else:
start()
+148
View File
@@ -0,0 +1,148 @@
# 美团小程序 mtgsig 出签客户端(本地补环境,不依赖浏览器/远端签名服务)
# 依赖常驻服务 mtgsig_js/serve.mjs,先跑 启动出签服务.py
import json
import urllib.parse
import requests
BASE_URL = 'http://127.0.0.1:18092'
SIGN_TIMEOUT = 60
PROXY = {'http': None, 'https': None}
def get_Datatext(dataq):
data = urllib.parse.urlencode(dataq)
return data
def js_encode_uri_component(s):
# 对齐 JS encodeURIComponent。表单对象用这个,query 的 fe 在纯算里另外做
return urllib.parse.quote('' if s is None else str(s), safe="-_.!~*'()")
def build_sign_data(data, content_type=''):
# 字符串原样返回(已经是要发出去的 body)。
# 字典:content_type 含 json → 紧凑 JSON;否则按键的插入顺序编成表单,不排序。
if data is None:
return ''
if isinstance(data, str):
return data
ct = (content_type or '').lower()
if 'json' in ct:
return json.dumps(data, ensure_ascii=False, separators=(',', ':'))
parts = []
for k, v in data.items():
parts.append(js_encode_uri_component(k) + '=' + js_encode_uri_component('' if v is None else v))
return '&'.join(parts)
def check_health():
r = requests.get(BASE_URL + '/health', timeout=5, proxies=PROXY)
r.raise_for_status()
return r.json()
def derive_from_mtgsig(mtgsig):
"""从一份 mtgsig(抓包里的旧签名即可)解出会话身份:appid / dfpid / localId / filetime"""
r = requests.post(BASE_URL + '/derive', json={'mtgsig': mtgsig}, timeout=SIGN_TIMEOUT, proxies=PROXY)
r.raise_for_status()
return r.json()
def get_mtgsig(url, data, mtgsig, open_id, method, mode=None, sys=None, ext=None, r=None, content_type=None):
"""按 url + body 出 mtgsig(url/data/mtgsig/open_id 必传)。跟具体接口路径无关。
mtgsig 传抓包里的旧签名,appid/dfpid/localId/filetime/a6 前缀会从它解出;
open_id 传请求头里的 openId(写入 a5 的 qn.b6,与抓包不一致会错签)。
method 传实际请求方法。GET/HEAD 的 data 不进签名。
content_type: 不传时,字符串按内容猜(以 { 或 [ 开头当 JSON,否则当表单),字典当表单。
JSON 接口传 'application/json'。只影响字典怎么编成 body,字符串原样参与签名。
data 传字符串 = 线上那个 body 原样(表单串或 JSON 串)。传字典时先编成字符串再签,
发出去的 body 必须用 build_sign_data(data, content_type) 的结果,不要另编一套。
url 的 query 会在纯算里统一规范化(解码、fe 重编码、按 key+value 排序),换接口只换 url 和 data。
url 里如果已经带了 mtgsig,会算进签名;重出签前先把这个参数从 url 去掉。
mode: 不传即走纯算(无预热、毫秒级);传 'bundle' 才用补环境跑 jsguard(每个新身份首次约 20s)。
sys/ext: 按字段名覆盖 a6 里的 system(46 项)/ext(5 项),只传要改的那几个,不传就原样。
sys 常用字段: brand/model/system/SDKVersion/version/screenWidth/screenHeight/pixelRatio/
brightness/fontSizeSetting/language/networkType/wifiEnabled/hasSystemProxy/
locationEnabled/bluetoothEnabled/deviceOrientation/LaunchOptionsSync 等(共 46 个,
完整清单见 serve.mjs 的 SYSTEM_FIELDS)
ext 字段: NativeClient / addEventListener / getPublicLibVersion / __WeixinJSBridge / NFC
仅纯算生效;字段名写错服务端会直接报错(并回可用字段名)。
"""
sign_data = build_sign_data(data, content_type or '')
body = {'url': url, 'data': sign_data, 'mtgsig': mtgsig, 'openId': open_id, 'method': method}
if content_type:
body['contentType'] = content_type
elif not isinstance(data, str):
body['contentType'] = 'application/x-www-form-urlencoded'
if mode:
body['mode'] = mode
if sys is not None:
body['sys'] = sys
if ext is not None:
body['ext'] = ext
if r is not None:
body['r'] = r
try:
resp = requests.post(BASE_URL + '/sign', json=body, timeout=SIGN_TIMEOUT, proxies=PROXY)
except requests.exceptions.ConnectionError:
raise RuntimeError('出签服务没启:先跑 `python 启动出签服务.py`(地址 %s)' % BASE_URL)
if resp.status_code != 200:
raise RuntimeError('出签失败 %s: %s' % (resp.status_code, resp.text[:200]))
return resp.json()['mtgsig']
def get_h5_sign(url, data, method, mode, profile, cookie='', data_type='json', type=None):
"""H5 出签(走服务里的 H5guard 补环境,非小程序 jsguard),返回整个结果 dict:
{mtgsig, url, headers, mode, a3, a6pfx}
url / data / method / mode / profile 必传(profile 缺字段服务端直接报错)。
profile = 设备/请求环境,全部来自抓包请求(没有内置默认身份):
ua, referrer, origin, chBrands(sec-ch-ua 原串), chPlatform(sec-ch-ua-platform),
chMobile(sec-ch-ua-mobile), language, languages(数组), platform, hardwareConcurrency,
deviceMemory, maxTouchPoints, screenWidth, screenHeight, availHeight, colorDepth,
devicePixelRatio, innerWidth, innerHeight, glVendor, glRenderer, appid, domains(数组)
可选: title / model / architecture / bitness / platformVersion
mode='sign':走手动 sign(),a6 前缀 h1.9 —— 外卖/买药 H5 页面自身 jquery 加签走这条。
mode='xhr':走 SDK 自己的 XHR 自动加签,a6 前缀 hs1.6 —— maf.meituan.com 这类接口要这个;
GET -> 用返回的 `url`(mtgsig 已拼进 query);POST -> 也用返回的 `url`。
cookie 可选(dfpid 走 mtgsig.a3)。服务按 profile 缓存环境,每个新 profile 首次等指纹预热。
"""
body = {'url': url, 'data': data, 'method': method, 'mode': mode, 'profile': profile,
'cookie': cookie, 'dataType': data_type, 'type': type or method}
try:
resp = requests.post(BASE_URL + '/sign_h5', json=body, timeout=SIGN_TIMEOUT, proxies=PROXY)
except requests.exceptions.ConnectionError:
raise RuntimeError('出签服务没启:先跑 `python 启动出签服务.py`(地址 %s)' % BASE_URL)
if resp.status_code != 200:
raise RuntimeError('H5 出签失败 %s: %s' % (resp.status_code, resp.text[:200]))
return resp.json()
def get_h5_mtgsig(url, data, method, mode, profile, cookie='', data_type='json', type=None):
"""只要 mtgsig 值本身时用这个(= get_h5_sign(...)['mtgsig'])。"""
return get_h5_sign(url=url, data=data, method=method, mode=mode, profile=profile, cookie=cookie, data_type=data_type, type=type)['mtgsig']
def get_h5_mtgsig_pure(url, data, mtgsig, method='POST', origin_url=None, origin_data=None):
"""外卖 H5(h1.9) **纯算**出签(不跑 SDK,毫秒级)—— 走服务里的 /sign_h5_pure。
mtgsig 传一份抓包里的 H5 mtgsig(a6 前缀 h1.9),url/data 传要出签的请求(data 是 form body 串);
origin_url/origin_data 是那份抓包签名对应的 url/data —— 只有要和出签请求不一样时才传(比如改了 body),
不传就按同一份包复算出签。换接口只换 url + data 即可(url/data/mtgsig/method 必传)。
"""
body = {'url': url, 'data': data, 'mtgsig': mtgsig, 'method': method}
if origin_url is not None:
body['origin_url'] = origin_url
if origin_data is not None:
body['origin_data'] = origin_data
try:
resp = requests.post(BASE_URL + '/sign_h5_pure', json=body, timeout=SIGN_TIMEOUT, proxies=PROXY)
except requests.exceptions.ConnectionError:
raise RuntimeError('出签服务没启:先跑 `python 启动出签服务.py`(地址 %s)' % BASE_URL)
if resp.status_code != 200:
raise RuntimeError('H5 纯算出签失败 %s: %s' % (resp.status_code, resp.text[:200]))
return resp.json()['mtgsig']
if __name__ == '__main__':
print(json.dumps(check_health(), ensure_ascii=False))