128 lines
3.7 KiB
Python
128 lines
3.7 KiB
Python
"""美团小程序 HTTP/1.1 发包公共模块 v3。依赖: pip install curl_cffi"""
|
|
|
|
import json
|
|
import threading
|
|
|
|
import requests as sign_requests
|
|
from curl_cffi import requests as mt_requests
|
|
from curl_cffi.const import CurlHttpVersion
|
|
from urllib.parse import parse_qs, quote, urlencode, urlparse, urlunparse
|
|
|
|
IMPERSONATE = None
|
|
FORCE_HTTP1 = True
|
|
|
|
MT_HEADER_ORDER = (
|
|
'Host', 'Connection', 'M-APPKEY', 'M-TRACEID', 'X-Requested-With',
|
|
'clientversion', 'content-type', 'csecuserid', 'csecuuid', 'mtgsig',
|
|
'openId', 'openIdCipher', 'token', 'utm_medium', 'uuid', 'x-env',
|
|
'charset', 'Referer', 'User-Agent', 'Accept-Encoding', 'wm-ctype',
|
|
)
|
|
SKIP_HEADER_KEYS = frozenset({'content-length'})
|
|
_tls = threading.local()
|
|
|
|
|
|
def get_mt_session():
|
|
if not hasattr(_tls, 'session'):
|
|
_tls.session = mt_requests.Session()
|
|
return _tls.session
|
|
|
|
|
|
def norm_coord(v):
|
|
if v is None:
|
|
return None
|
|
return str(v).split('.')[0]
|
|
|
|
|
|
def build_mt_headers(raw_headers: dict, mtgsig: str) -> list[tuple[str, str]]:
|
|
merged = dict(raw_headers)
|
|
merged['mtgsig'] = mtgsig
|
|
lower_map = {k.lower(): k for k in merged}
|
|
ordered: list[tuple[str, str]] = []
|
|
used = set()
|
|
for name in MT_HEADER_ORDER:
|
|
lk = name.lower()
|
|
if lk in SKIP_HEADER_KEYS or lk in used:
|
|
continue
|
|
orig = lower_map.get(lk)
|
|
if orig is None:
|
|
continue
|
|
ordered.append((orig, str(merged[orig])))
|
|
used.add(lk)
|
|
for k, v in merged.items():
|
|
lk = k.lower()
|
|
if lk in used or lk in SKIP_HEADER_KEYS:
|
|
continue
|
|
ordered.append((k, str(v)))
|
|
return ordered
|
|
|
|
|
|
def patch_url(url: str, lat, lng, req_time) -> str:
|
|
url_data = urlparse(url)
|
|
params = parse_qs(url_data.query, keep_blank_values=True)
|
|
params['req_time'] = [str(req_time)]
|
|
if lat is not None and lng is not None:
|
|
lat_s, lng_s = norm_coord(lat), norm_coord(lng)
|
|
for key, val in (
|
|
('wm_longitude', lng_s), ('wm_latitude', lat_s),
|
|
('longitude', lng_s), ('latitude', lat_s),
|
|
('wm_actual_longitude', lng_s), ('wm_actual_latitude', lat_s),
|
|
):
|
|
params[key] = [val]
|
|
new_query = urlencode(params, doseq=True, quote_via=quote)
|
|
return urlunparse(
|
|
(url_data.scheme, url_data.netloc, url_data.path, url_data.params, new_query, url_data.fragment)
|
|
)
|
|
|
|
|
|
def is_yoda_block(text: str) -> bool:
|
|
if '您的网络好像不太给力' in text:
|
|
return True
|
|
try:
|
|
return json.loads(text).get('yodaCode') == 406
|
|
except Exception:
|
|
return False
|
|
|
|
|
|
def mt_post(url, header_list, body: str, proxies):
|
|
kwargs = {
|
|
'headers': header_list,
|
|
'data': body,
|
|
'verify': False,
|
|
'proxies': proxies,
|
|
'timeout': 60,
|
|
}
|
|
if FORCE_HTTP1:
|
|
kwargs['http_version'] = CurlHttpVersion.V1_1
|
|
if IMPERSONATE:
|
|
kwargs['impersonate'] = IMPERSONATE
|
|
return get_mt_session().post(url, **kwargs)
|
|
|
|
|
|
def get_sign_new1(url, data, dfpid, mtg_origin, openId):
|
|
headers = {'content-type': 'application/json', 'token': 'test_sdfio23923ojbedfojgbouqgew4r32dds'}
|
|
body = {
|
|
'mtg_origin': mtg_origin,
|
|
'url': url,
|
|
'data': data,
|
|
'dfpid': dfpid,
|
|
'method': 'POST',
|
|
'open_id': openId,
|
|
}
|
|
sign_url = 'http://129.211.12.35:18003/minipro_mt_0206'
|
|
req = sign_requests.post(
|
|
sign_url, headers=headers, json=body,
|
|
proxies={'http': None, 'https': None}, verify=False,
|
|
).text
|
|
print(req)
|
|
return req
|
|
|
|
|
|
def normalize_proxies(prox):
|
|
if not prox:
|
|
return {'http': None, 'https': None}
|
|
out = {}
|
|
for k, v in prox.items():
|
|
v = str(v).replace('socks5://', 'http://').replace('socks5s://', 'https://')
|
|
out[k] = v
|
|
return out
|