diff --git a/run5_mp.py b/run5_mp.py new file mode 100644 index 0000000..d159a0b --- /dev/null +++ b/run5_mp.py @@ -0,0 +1,1258 @@ +""" +商品详情请求 run5_mp:run5 原逻辑 + 多进程。 +点运行即按 PROCESS_COUNT 开多个进程,每个进程就是一份 run5。 +包/商品按 id 取模切开,互不抢。 +""" +import json +import os +import queue +import random +import multiprocessing +import threading +import time +import urllib.parse +from collections import defaultdict +from concurrent.futures import ThreadPoolExecutor, as_completed +from pathlib import Path +import newsetting as ten +import requests as sign_requests +from urllib.parse import parse_qs, parse_qsl, quote, urlencode, urlparse, urlunparse +import asyncio, json, uuid +import websockets + +# ==================== 运行参数(改这里) ==================== +tent = ten.All_Setting(host='192.168.5.2', port=3307, db='headers_project') +tent2 = ten.All_Setting(host='183.6.7.91', port=33016, db='mt_newretail') +# 药品详情机器人的部分参数 +BOT_ID = "aibWks3RnhEq3uYpq40Dkx5u3usRHh3kHom" +SECRET = "HoY5rDAi8cHw6pmUeu3lpfyJSj1OQOwUhDe3HSWCWD4" +WS_URL = "wss://openws.work.weixin.qq.com" +CHAT_ID = "wrfDGnMQAAze96sNBGmEaoOYtT-PvvoQ" +MAX_WORKERS = 5 # 并行线程数;当前包废了自动接下一个。0=按可用包数全开 +Interval_time = 5 # 分钟间隔(用来修改入库后到请求的闲置时间) +REQUEST_INTERVAL = 0.1 # 每包两次美团请求间隔(秒) +INTERVAL_JITTER = 0.5 # 额外随机 0~N 秒 +STAGGER_START = 0.3 # 各包启动错开 +COOLDOWN_SEC = 0 # 每个包启动前再等 N 秒(刚抓完建议 >=180;包已冷却可改 0) +COORD_MODE = 'capture' +BACKEND = 'requests' # 'requests' | 'curl' +IMPERSONATE = None +FORCE_HTTP1 = True +STOP_PACKAGE_ON_YODA = True +AUTO_CONTINUE_HD = True # 本轮结束后查表还有 is_ok is null 的包就自动接上 +HD_RECHECK_SEC = 5 # 接下一轮前等待秒数(给插包/落库一点缓冲;0=立刻) +PROCESS_COUNT = 3 # 开几个进程,改这里 +PKG_EMPTY_POLL_SEC = 300 # 全库无包时,隔多久再查一次表 +PKG_ALERT_SEC = 1800 # 同一条「无可用药店详情包」群告警的最短间隔 +HD_USING = 2 # 包领取中。表里已有 403/418/777/7777,不能占用 +ITEM_USING = 'using' # 商品领取中。is_ok 是字符串,2/9 已有业务含义 +CLAIM_EXPIRE_SEC = 1800 # 进程挂死后,超时的「领取中」放回空 +# 任务城市 → proxs_list 省会(库里 city 无「市」) +CITY_TO_CAPITAL = { + '郑州市': '郑州', + '上海市': '上海', + '西安市': '西安', + '长沙市': '长沙', + '重庆市': '重庆', + '哈尔滨市': '哈尔滨', + '成都市': '成都', + '北京市': '北京', + '天津市': '天津', + '杭州市': '杭州', + '广州市': '广州', + '深圳市': '广州', + '合肥市': '合肥', + '沈阳市': '沈阳', + '南京市': '南京', + '东莞市': '广州', + '青岛市': '济南', + '佛山市': '广州', + '武汉市': '武汉', + '苏州市': '南京', +} +# 额外兜底坐标 +FALLBACK_LOCATION = [ + # 哈尔滨 + ('45774984', '126617714'), + # 长春 + ('43886770', '125322780'), + # 西安 + ('34261004', '108942336'), +] +# 额外兜底代理 +FALLBACK_PROX = [ + # 哈尔滨 + {"http": "http://uuvg:uuvgt@122.246.5.154:20754", "https": "http://uuvg:uuvgt@122.246.5.154:20754"}, + # 长春 + {'http': 'http://uuvg:uuvgt@122.246.5.149:21197', 'https': 'http://uuvg:uuvgt@122.246.5.149:21197'}, + # 西安 + {"http": "http://uuvg:uuvgt@122.246.5.148:21168", "https": "http://uuvg:uuvgt@122.246.5.148:21168"} +] +# 请求头部排序以及参数 +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', +) +# ============================================================ +# requests 自己管 Host;Content-Length 交给库算 +SKIP_HEADER_KEYS = frozenset({'content-length'}) +SKIP_HEADER_KEYS_REQUESTS = frozenset({'content-length', 'host'}) + +SCRIPT_DIR = Path(__file__).resolve().parent +PKG_CITY_MAP_PATH = SCRIPT_DIR / 'pkg_city_map.json' +PROC_ID = 0 + +_tls = threading.local() +_log_lock = threading.Lock() +_stats_lock = threading.Lock() +_stats = {'ok': 0, 'fail': 0, 'yoda': 0, 'done_packages': 0} +_verify_logged_ids: set[str] = set() +_verify_log_lock = threading.Lock() +_last_pkg_alert_at = 0.0 + + +async def send(content: str): + async with websockets.connect("wss://openws.work.weixin.qq.com") as ws: + await ws.send(json.dumps({ + "cmd": "aibot_subscribe", + "headers": {"req_id": uuid.uuid4().hex}, + "body": {"bot_id": BOT_ID, "secret": SECRET}, + })) + assert json.loads(await ws.recv()).get("errcode") == 0, "鉴权失败,检查BotID/Secret" + + req_id = uuid.uuid4().hex + await ws.send(json.dumps({ + "cmd": "aibot_send_msg", + "headers": {"req_id": req_id}, + "body": { + "chatid": CHAT_ID, + "chat_type": 2, # 2=群聊,1=单聊 + "msgtype": "markdown", # 也支持 text / template_card + "markdown": {"content": content}, + }, + })) + async for raw in ws: + frame = json.loads(raw) + if frame.get("headers", {}).get("req_id") == req_id: # 跳过杂散的回调帧,只收本条应答 + print("发送结果:", frame) # errcode=0 即成功 + break + + +def library_has_package() -> bool: + """全库还有空包,或包正在被别的电脑领着用。这两种都不算「库里没包」。""" + sql = f''' + select `id` from medince_item_hd + where is_ok is null or is_ok = {int(HD_USING)} + limit 1 + ''' + return bool(tent.get_shoppingmalls(sql)) + + +def claim_pkg_alert() -> bool: + """多份 run5_mp 同时跑时共用一条库记录。间隔内只有一个进程能抢到。""" + global _last_pkg_alert_at + now = time.time() + if _last_pkg_alert_at and now - _last_pkg_alert_at < PKG_ALERT_SEC: + wait = int(PKG_ALERT_SEC - (now - _last_pkg_alert_at)) + print(f'[p{PROC_ID}] 库中仍无可用药店详情包,{wait}s 内不再推群') + return False + conn = tent.get_conn() + cur = conn.cursor() + try: + cur.execute(''' + CREATE TABLE IF NOT EXISTS `pkg_alert_state` ( + `alert_key` varchar(64) NOT NULL, + `alert_at` datetime NOT NULL, + PRIMARY KEY (`alert_key`) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 + ''') + cur.execute(''' + INSERT INTO `pkg_alert_state` (`alert_key`, `alert_at`) + VALUES ('medince_item_hd_empty', NOW()) + ON DUPLICATE KEY UPDATE + `alert_at` = IF(`alert_at` < NOW() - INTERVAL %s SECOND, NOW(), `alert_at`) + ''', (int(PKG_ALERT_SEC),)) + conn.commit() + # 1=新插入,2=间隔已过并更新;0=别的进程刚写过,这次不发 + won = cur.rowcount in (1, 2) + _last_pkg_alert_at = now + if not won: + print(f'[p{PROC_ID}] 已有其他 run5_mp 发过头部包告警,{PKG_ALERT_SEC}s 内不再推群') + return won + finally: + cur.close() + conn.close() + + +def alert_no_package(): + """全库没包、且还有商品时才推群。每份脚本只由 0 号进程去抢,多开也只发一条。""" + if PROC_ID != 0: + return + if library_has_package(): + return + try: + if not claim_pkg_alert(): + return + asyncio.run(send("**头部包告警** 库中没有可用的药店详情包")) + except Exception as e: + print(f'[p{PROC_ID}] 头部包告警发送失败: {e}') + + +def log(tag: str, msg: str): + with _log_lock: + print(f'[p{PROC_ID}] [{tag}] {msg}') + + +def bump_stat(key: str, n: int = 1): + with _stats_lock: + _stats[key] = _stats.get(key, 0) + n + + +def sleep_interval(): + delay = max(0.0, REQUEST_INTERVAL) + random.uniform(0, max(0.0, INTERVAL_JITTER)) + if delay > 0: + time.sleep(delay) + + +def _prox_key(proxies) -> str: + if not proxies: + return '' + if isinstance(proxies, dict): + return str(proxies.get('https') or proxies.get('http') or '') + return str(proxies) + + +def reset_mt_session(): + sess = getattr(_tls, 'session', None) + if sess is not None: + try: + sess.close() + except Exception: + pass + _tls.session = None + _tls.prox_key = None + + +def get_mt_session(proxies=None): + key = _prox_key(proxies) + if getattr(_tls, 'session', None) is not None and getattr(_tls, 'prox_key', None) != key: + reset_mt_session() + if getattr(_tls, 'session', None) is None: + if BACKEND == 'curl': + from curl_cffi import requests as mt_requests + _tls.session = mt_requests.Session() + else: + _tls.session = sign_requests.Session() + _tls.prox_key = key + return _tls.session + + +def normalize_headers(raw): + """抓包可能是 dict,也可能是 [[k,v],...] 列表(curl/mitm 常见)。""" + if isinstance(raw, dict): + return dict(raw) + if isinstance(raw, (list, tuple)): + out = {} + for item in raw: + if isinstance(item, (list, tuple)) and len(item) >= 2: + out[str(item[0])] = item[1] + return out + raise TypeError(f'unsupported headers type: {type(raw).__name__}') + + +def get_Datatext(dataq): + return '&'.join(f'{k}={dataq[k]}' for k in dataq) + + +def get_sign_new1(url, data, dfpid, mtg_origin, openId, tag='sign'): + 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 + log(tag, f'签名返回: {req[:120]}...' if len(req) > 120 else f'签名返回: {req}') + return req + + +def build_mt_headers(raw_headers: dict, mtgsig: str): + merged = dict(raw_headers) + merged['mtgsig'] = mtgsig + skip = SKIP_HEADER_KEYS_REQUESTS if BACKEND == 'requests' else SKIP_HEADER_KEYS + 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 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: + continue + ordered.append((k, str(v))) + if BACKEND == 'curl': + return ordered + return dict(ordered) + + +def mt_post(url, headers, body: str, proxies): + kwargs = { + 'headers': headers, + 'data': body, + 'verify': False, + 'proxies': proxies, + 'timeout': 30, + } + session = get_mt_session(proxies) + if BACKEND == 'curl': + from curl_cffi.const import CurlHttpVersion + if FORCE_HTTP1: + kwargs['http_version'] = CurlHttpVersion.V1_1 + if IMPERSONATE: + kwargs['impersonate'] = IMPERSONATE + return session.post(url, **kwargs) + + +def extract_capture_latlng(url: str, data: dict): + """从抓包 URL / body 取坐标,优先 body。""" + for lat_k, lng_k in ( + ('wm_latitude', 'wm_longitude'), + ('latitude', 'longitude'), + ('wm_actual_latitude', 'wm_actual_longitude'), + ): + lat, lng = data.get(lat_k), data.get(lng_k) + if lat and lng and str(lat) not in ('0', 'None') and str(lng) not in ('0', 'None'): + return str(lat).split('.')[0], str(lng).split('.')[0], f'capture-body:{lat_k}' + params = parse_qs(urlparse(url).query, keep_blank_values=True) + for lat_k, lng_k in ( + ('wm_latitude', 'wm_longitude'), + ('latitude', 'longitude'), + ('wm_actual_latitude', 'wm_actual_longitude'), + ): + lat = (params.get(lat_k) or [None])[0] + lng = (params.get(lng_k) or [None])[0] + if lat and lng and lat not in ('0',) and lng not in ('0',): + return str(lat).split('.')[0], str(lng).split('.')[0], f'capture-url:{lat_k}' + return None, None, 'capture-miss' + + +def resolve_location(hd, slot: int, url: str, data: dict): + """按 COORD_MODE 选坐标(代理改由任务城市→省会从 proxs_list 取)。""" + hd_ind, db_lat, db_lng = hd[0], hd[2], hd[3] + cap_lat, cap_lng, cap_src = extract_capture_latlng(url, data) + + if COORD_MODE == 'db' and db_lat and db_lng: + return hd_ind, str(db_lat), str(db_lng), 'db' + if COORD_MODE == 'db_else_capture': + if db_lat and db_lng: + return hd_ind, str(db_lat), str(db_lng), 'db' + if cap_lat and cap_lng: + return hd_ind, cap_lat, cap_lng, cap_src + if COORD_MODE == 'capture' and cap_lat and cap_lng: + return hd_ind, cap_lat, cap_lng, cap_src + + if cap_lat and cap_lng: + return hd_ind, cap_lat, cap_lng, cap_src + if db_lat and db_lng: + return hd_ind, str(db_lat), str(db_lng), 'db' + latitude, longitude = FALLBACK_LOCATION[slot % len(FALLBACK_LOCATION)] + return hd_ind, latitude, longitude, 'fallback-pool' + + +def _parse_prox_row(prox_data, ip_address=None, port=None, acount=None, pwd=None): + if isinstance(prox_data, str) and prox_data.strip(): + try: + prox_data = json.loads(prox_data) + except Exception: + prox_data = None + if isinstance(prox_data, dict) and (prox_data.get('http') or prox_data.get('https')): + return prox_data + if ip_address and port: + auth = f'{acount}:{pwd}@' if acount else '' + url = f'http://{auth}{ip_address}:{port}' + return {'http': url, 'https': url} + return None + + +def load_proxs() -> dict: + """从 project_proxy.proxs_list 加载 {省会: prox_dict}。""" + rows = tent.get_shoppingmalls( + 'SELECT city, prox_data, ip_address, port, acount, pwd FROM project_proxy.proxs_list' + ) + proxs = {} + for row in rows or []: + city = str(row[0]).strip() if row[0] else '' + if not city: + continue + prox = _parse_prox_row(*row[1:6]) if len(row) >= 6 else _parse_prox_row(row[1]) + if prox: + proxs[city] = prox + return proxs + + +def city_to_capital(city: str) -> str: + name = (city or '').strip() + if not name: + return '' + if name in CITY_TO_CAPITAL: + return CITY_TO_CAPITAL[name] + if name + '市' in CITY_TO_CAPITAL: + return CITY_TO_CAPITAL[name + '市'] + bare = name[:-1] if name.endswith('市') else name + return CITY_TO_CAPITAL.get(bare + '市', bare) + + +def _is_empty_city(city: str) -> bool: + name = (city or '').strip() + return (not name) or name in ('_empty', 'None', 'null') + + +def pick_random_proxy(proxs: dict): + pool = [p for p in (proxs or {}).values() if p] or list(FALLBACK_PROX) + return random.choice(pool) if pool else None + + +def alloc_city_proxy(city: str): + """输入任务城市,返回对应省会在 proxs_list 里的代理。city 为空则随机一条。""" + if _is_empty_city(city): + return None + capital = city_to_capital(city) + if not capital: + return None + sql = f''' + SELECT city, prox_data, ip_address, port, acount, pwd + FROM project_proxy.proxs_list + WHERE city = '{capital}' + LIMIT 1 + ''' + rows = tent.get_shoppingmalls(sql) + if not rows: + sql = f''' + SELECT city, prox_data, ip_address, port, acount, pwd + FROM project_proxy.proxs_list + WHERE city LIKE '%{capital}%' + LIMIT 1 + ''' + rows = tent.get_shoppingmalls(sql) + if not rows: + return None + return _parse_prox_row(*rows[0][1:6]) + + +def get_capital_proxy(city: str, proxs: dict, slot: int = 0): + """任务城市 → 省会 → proxs_list;city 为空走随机代理;没有则 alloc_city_proxy;再没有才兜底。""" + if _is_empty_city(city): + prox = pick_random_proxy(proxs) + if prox: + return prox, 'random', '' + prox = FALLBACK_PROX[slot % len(FALLBACK_PROX)] + return prox, 'fallback', '' + capital = city_to_capital(city) + if capital and capital in proxs: + return proxs[capital], f'proxs_list:{capital}', capital + for pro_city, prox_data in proxs.items(): + if capital and (capital in pro_city or pro_city in capital): + return prox_data, f'proxs_list~:{pro_city}', capital + if city and (city in pro_city or pro_city in city): + return prox_data, f'proxs_list~:{pro_city}', capital + extra = alloc_city_proxy(city) + if extra: + return extra, 'alloc_city_proxy', capital + prox = FALLBACK_PROX[slot % len(FALLBACK_PROX)] + return prox, 'fallback', capital + + +def _norm_city(city) -> str: + name = (city or '').strip() + return name or '_empty' + + +def _empty_pkg_record(city: str, ok: int = 0, fail: int = 0) -> dict: + return {'city': _norm_city(city), 'ok': int(ok), 'fail': int(fail)} + + +def load_pkg_city_map() -> dict: + if not PKG_CITY_MAP_PATH.exists(): + return {} + try: + data = json.loads(PKG_CITY_MAP_PATH.read_text(encoding='utf-8')) + except Exception as e: + print(f'pkg_city_map 读取失败,当作空: {e}') + return {} + if not isinstance(data, dict): + return {} + out = {} + for k, v in data.items(): + pid = str(k) + if not pid: + continue + if isinstance(v, dict): + city = _norm_city(v.get('city')) + if not city: + continue + out[pid] = _empty_pkg_record(city, v.get('ok') or 0, v.get('fail') or 0) + elif v: + out[pid] = _empty_pkg_record(v) + return out + + +def save_pkg_city_map(mapping: dict): + tmp = PKG_CITY_MAP_PATH.with_suffix('.json.tmp') + tmp.write_text(json.dumps(mapping, ensure_ascii=False, indent=2), encoding='utf-8') + tmp.replace(PKG_CITY_MAP_PATH) + + +def _pkg_city_name(rec) -> str: + if isinstance(rec, dict): + return rec.get('city') or '' + return _norm_city(rec) + + +class CityAssigner: + """有名城市尽量一包一城;没城市的任务和多出来的包均分,避免闲置。""" + + def __init__(self, items, live_pkg_ids, known_pkg_ids=None): + self._lock = threading.Lock() + self.live_pkg_ids = {str(x) for x in live_pkg_ids} + known = {str(x) for x in (known_pkg_ids if known_pkg_ids is not None else live_pkg_ids)} + self.queues: dict[str, queue.Queue] = {} + grouped = defaultdict(list) + for row in items or []: + grouped[_norm_city(row[4] if len(row) > 4 else '')].append(row) + for city, rows in grouped.items(): + q = queue.Queue() + for row in rows: + q.put(row) + self.queues[city] = q + self.pkg_city = load_pkg_city_map() + self.live: dict[str, str] = {} + stale = [pid for pid in self.pkg_city if pid not in known] + for pid in stale: + self.pkg_city.pop(pid, None) + if stale: + save_pkg_city_map(self.pkg_city) + + def add_live(self, pkg_id): + with self._lock: + self.live_pkg_ids.add(str(pkg_id)) + + def city_counts(self) -> dict: + return {c: q.qsize() for c, q in sorted(self.queues.items())} + + def remaining(self) -> int: + return sum(q.qsize() for q in self.queues.values()) + + def leftover(self, city: str) -> int: + q = self.queues.get(city) + return q.qsize() if q else 0 + + def dump_bindings(self) -> dict: + return { + pid: f"{_pkg_city_name(rec)} ok={rec.get('ok', 0)} fail={rec.get('fail', 0)}" + if isinstance(rec, dict) else str(rec) + for pid, rec in self.pkg_city.items() + } + + def bind(self, pkg_id) -> str | None: + pid = str(pkg_id) + with self._lock: + sticky = _pkg_city_name(self.pkg_city.get(pid)) + if sticky and self._city_has_work(sticky): + if _is_empty_city(sticky) or not self._held_by_other(pid, sticky): + self.live[pid] = sticky + return sticky + + exclusive = self._pick_exclusive_named(pid) + if exclusive: + return self._set_bind(pid, exclusive) + + # 没名城可独占的包:先均分空城,再去任务最多的名城帮忙 + if self._city_has_work('_empty'): + return self._set_bind(pid, '_empty') + + share = self._pick_share_named() + if share: + return self._set_bind(pid, share) + + self.live.pop(pid, None) + return None + + def _pick_exclusive_named(self, pid: str) -> str | None: + reserved = set() + for other_pid, rec in self.pkg_city.items(): + if other_pid != pid and other_pid in self.live_pkg_ids: + c = _pkg_city_name(rec) + if c and not _is_empty_city(c): + reserved.add(c) + for city, q in self.queues.items(): + if _is_empty_city(city) or q.qsize() <= 0: + continue + if city in reserved: + continue + if self._workers_on(city) > 0: + continue + return city + return None + + def _pick_share_named(self) -> str | None: + best, best_score = None, -1.0 + for city, q in self.queues.items(): + if _is_empty_city(city): + continue + n = q.qsize() + if n <= 0: + continue + score = n / (self._workers_on(city) + 1) + if score > best_score: + best, best_score = city, score + return best + + def _workers_on(self, city: str) -> int: + return sum(1 for c in self.live.values() if c == city) + + def _set_bind(self, pid: str, city: str) -> str: + old = self.pkg_city.get(pid) if isinstance(self.pkg_city.get(pid), dict) else {} + self.pkg_city[pid] = _empty_pkg_record( + city, (old or {}).get('ok') or 0, (old or {}).get('fail') or 0 + ) + self.live[pid] = city + save_pkg_city_map(self.pkg_city) + return city + + def bump(self, pkg_id, key: str = 'ok') -> dict: + pid = str(pkg_id) + with self._lock: + rec = self.pkg_city.get(pid) + if not isinstance(rec, dict): + rec = _empty_pkg_record(self.live.get(pid) or rec or '') + self.pkg_city[pid] = rec + rec[key] = int(rec.get(key) or 0) + 1 + save_pkg_city_map(self.pkg_city) + return dict(rec) + + def take(self, city: str): + q = self.queues.get(city) + if q is None: + raise queue.Empty + return q.get_nowait() + + def mark_done(self, pkg_id): + """包被风控/403 废掉:放开城市,下次别的包可接。计数保留到该包被清掉。""" + pid = str(pkg_id) + with self._lock: + self.live.pop(pid, None) + self.live_pkg_ids.discard(pid) + if pid in self.pkg_city: + self.pkg_city.pop(pid, None) + save_pkg_city_map(self.pkg_city) + + def finish_city(self, pkg_id): + pid = str(pkg_id) + with self._lock: + self.live.pop(pid, None) + + def _city_has_work(self, city: str) -> bool: + q = self.queues.get(city) + return bool(q and q.qsize() > 0) + + def _held_by_other(self, pid: str, city: str) -> bool: + for other, c in self.live.items(): + if other != pid and c == city: + return True + return False + + +def get_headers(): + shard = '' if PROCESS_COUNT <= 1 else f' AND MOD(`id`, {PROCESS_COUNT}) = {PROC_ID}' + overtime = f" AND `updated_at` < NOW() - INTERVAL {Interval_time} MINUTE" + sql = f''' + select `id`,json_data,lat,lng,prox from medince_item_hd where is_ok is null{shard}{overtime} + ''' + return tent.get_shoppingmalls(sql) or [] + + +def get_headers1(): + shard = '' if PROCESS_COUNT <= 1 else f' AND MOD(`id`, {PROCESS_COUNT}) = {PROC_ID}' + sql = f''' + select `id`,json_data,lat,lng,prox from medince_item_hd where is_ok is null{shard} + ''' + return tent.get_shoppingmalls(sql) or [] + + +def get_items(): + # 商品不按进程切:包 id 和商品 id 不是一套,切开后会出现「表里有任务、本进程却说没有」 + sql = ''' + select `id`,`mt_org_id`,product_id,upccode,city + FROM `mt_newretail`.`drug_detail_list` WHERE is_ok is null + ''' + return tent2.get_shoppingmalls(sql) or [] + + +def item_still_pending(ind) -> bool: + sql = f''' + select `id` from drug_detail_list where `id` = {int(ind)} and is_ok is null + ''' + return bool(tent2.get_shoppingmalls(sql)) + + +def update_headers(ind, is_ok, json_data=''): + if is_ok == 1: + sql = ''' + UPDATE medince_item_hd + SET req_count = COALESCE(req_count, 0) + 1, + current_count = COALESCE(current_count, 0) + 1 + WHERE `id` = %s + ''' + tent.write_data_one(sql, (ind,)) + return + if is_ok == 418: + sql = ''' + update medince_item_hd set is_ok=%s,json_data=%s where `id`=%s + ''' + tent.write_data(sql, ((is_ok, json_data, ind),)) + return + sql = ''' + update medince_item_hd set is_ok=%s where `id`=%s + ''' + tent.write_data_one(sql, (is_ok, ind)) + + +def save_item(ind, data): + sql = ''' + insert into save_item (parent_id,json_data) values (%s,%s) + ''' + tent2.write_data(sql, ((ind, data),)) + + +def update_item(ind, is_ok=1): + sql = ''' + update drug_detail_list set is_ok=%s where `id`=%s + ''' + tent2.write_data(sql, ((is_ok, ind),)) + + +def _exec_rowcount(db, sql, args=None) -> int: + conn = db.get_conn() + cur = conn.cursor() + try: + cur.execute(sql, args) + conn.commit() + return int(cur.rowcount or 0) + finally: + cur.close() + conn.close() + + +def claim_header(ind) -> bool: + """不同电脑同时领同一个包时,只有一行能从空改成领取中。""" + sql = ''' + update medince_item_hd set is_ok=%s where `id`=%s and is_ok is null + ''' + return _exec_rowcount(tent, sql, (HD_USING, ind)) == 1 + + +def release_header(ind): + """包还活着就放回空。403/418/500 已经写上终态,这里改不到。""" + sql = ''' + update medince_item_hd set is_ok=null where `id`=%s and is_ok=%s + ''' + try: + _exec_rowcount(tent, sql, (ind, HD_USING)) + except Exception as e: + print(f'[p{PROC_ID}] 放回包 {ind} 失败: {e}') + + +_hd_touch_at: dict = {} + + +def touch_header(ind): + """长跑时刷新 updated_at,避免被超时回收抢走。""" + now = time.time() + if now - _hd_touch_at.get(ind, 0) < 60: + return + _hd_touch_at[ind] = now + sql = ''' + update medince_item_hd set updated_at=NOW() where `id`=%s and is_ok=%s + ''' + try: + _exec_rowcount(tent, sql, (ind, HD_USING)) + except Exception as e: + print(f'[p{PROC_ID}] 刷新包 {ind} 领取时间失败: {e}') + + +def claim_item(ind) -> bool: + sql = ''' + update drug_detail_list set is_ok=%s where `id`=%s and is_ok is null + ''' + return _exec_rowcount(tent2, sql, (ITEM_USING, ind)) == 1 + + +def release_item(ind): + sql = ''' + update drug_detail_list set is_ok=null where `id`=%s and is_ok=%s + ''' + try: + _exec_rowcount(tent2, sql, (ind, ITEM_USING)) + except Exception as e: + print(f'[p{PROC_ID}] 放回商品 {ind} 失败: {e}') + + +def release_stale_claims(): + """进程被杀掉时,领取中会卡住。超时后放回,别的电脑才能再领。""" + hd_n = _exec_rowcount(tent, ''' + update medince_item_hd set is_ok=null + where is_ok=%s and updated_at < NOW() - INTERVAL %s SECOND + ''', (HD_USING, int(CLAIM_EXPIRE_SEC))) + item_n = _exec_rowcount(tent2, ''' + update drug_detail_list set is_ok=null + where is_ok=%s and update_time < NOW() - INTERVAL %s SECOND + ''', (ITEM_USING, int(CLAIM_EXPIRE_SEC))) + if hd_n or item_n: + print(f'[p{PROC_ID}] 放回超时领取 hd={hd_n} 商品={item_n}') + + +def append_verify_log_once(package_id, content: str) -> bool: + pid = str(package_id) + with _verify_log_lock: + if pid in _verify_logged_ids: + return False + _verify_logged_ids.add(pid) + log_path = os.path.join( + os.path.dirname(os.path.abspath(__file__)), + 'verify_log.json' if PROCESS_COUNT <= 1 else f'verify_log.p{PROC_ID}.json', + ) + with open(log_path, 'a', encoding='utf-8') as f: + f.write(content.rstrip()) + f.write(',\n\n') + return True + + +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 describe_block(text: str) -> str: + try: + j = json.loads(text) + if j.get('yodaCode') == 406: + risk = (j.get('customData') or {}).get('riskLevel', '?') + return f'yoda406 riskLevel={risk}' + except Exception: + pass + if '您的网络好像不太给力' in text: + return '网络不好(yoda)' + if '403' in text or 'Forbidden' in text: + return '403' + return 'unknown' + + +def build_variables_str(poi_id_str, spu_id, sku_id) -> str: + """必须是 JSON 双引号,和微信小程序一致;勿用 str(dict)。""" + varib = { + 'wm_poi_id': '-100', + 'poi_id_str': str(poi_id_str), + 'spu_id': str(spu_id), + 'sku_id': str(sku_id if sku_id not in (None, '', 'null') else '0'), + 'spu_tag': 'null', + 'activity_tag': 'null', + 'share_activity_uuid': 'null', + 'sale_type': '0', + 'outer_upload_key': 'clickid', + } + raw = json.dumps(varib, ensure_ascii=False, separators=(',', ':')) + return quote(raw, safe='') + + +def apply_coords(data: dict, url: str, latitude: str, longitude: str, req_time: str): + data['wm_latitude'] = latitude + data['wm_longitude'] = longitude + data['latitude'] = latitude + data['longitude'] = longitude + data['wm_actual_latitude'] = latitude + data['wm_actual_longitude'] = longitude + data['req_time'] = req_time + url_data = urlparse(url) + params = parse_qs(url_data.query, keep_blank_values=True) + params['req_time'] = [req_time] + for key, val in ( + ('wm_longitude', longitude), ('wm_latitude', latitude), + ('longitude', longitude), ('latitude', latitude), + ('wm_actual_longitude', longitude), ('wm_actual_latitude', latitude), + ): + 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) + ), data + + +def run_package(hd, assigner: CityAssigner, slot: int, start_delay: float, proxs: dict) -> str: + """跑一个抓包。switch=包废了换下一个;stop=没任务/正常结束。""" + if start_delay > 0: + time.sleep(start_delay) + + hd_ind = hd[0] + tag = f'pkg-{hd_ind}' + reset_mt_session() + try: + url0, headers0, data0 = json.loads(hd[1]) + headers0 = normalize_headers(headers0) + if isinstance(data0, str): + data0 = dict(parse_qsl(data0, keep_blank_values=True)) + except Exception as e: + log(tag, f'包数据损坏,标记跳过并换下一个: {e}') + update_headers(hd_ind, 500) + assigner.mark_done(hd_ind) + bump_stat('done_packages') + return 'switch' + + hd_ind, latitude, longitude, loc_source = resolve_location(hd, slot, url0, data0) + tag = f'pkg-{hd_ind}' + url, headers, data = url0, headers0, dict(data0) + + log( + tag, + f'启动 backend={BACKEND} coord_mode={COORD_MODE} loc={loc_source} ' + f'lat={latitude} lng={longitude} 一包一城(落盘 pkg_city_map.json)' + ) + if loc_source.startswith('fallback'): + log(tag, '警告: 坐标走了兜底池,新号极易秒死,请改 COORD_MODE=capture 或补 lat/lng') + + if COOLDOWN_SEC > 0: + log(tag, f'包冷却等待 {COOLDOWN_SEC}s(刚抓完务必等;已冷却可把 COOLDOWN_SEC=0)') + time.sleep(COOLDOWN_SEC) + + pkg_ok = 0 + old_rec = assigner.pkg_city.get(str(hd_ind)) + if isinstance(old_rec, dict): + pkg_ok = int(old_rec.get('ok') or 0) + if pkg_ok: + log(tag, f'续跑计数 ok={pkg_ok} fail={old_rec.get("fail", 0)} 原城市={old_rec.get("city")}') + try: + while True: + city = assigner.bind(hd_ind) + if not city: + log(tag, f'无待跑城市,本包结束,成功 {pkg_ok} 条') + bump_stat('done_packages') + return 'stop' + + prox, prox_src, capital = get_capital_proxy(city, proxs, slot) + reset_mt_session() + prox_host = (prox.get('http') or '')[:60] + city_show = city if not _is_empty_city(city) else '(空)' + log( + tag, + f'绑定城市={city_show} → {capital or "-"} src={prox_src} ' + f'本城包数={assigner._workers_on(city)} 剩余={assigner.leftover(city)} proxy={prox_host}' + ) + if prox_src == 'random': + log(tag, 'city 为空,已随机一条代理') + elif prox_src == 'fallback': + log(tag, f'警告: city={city_show} 无代理,走兜底池') + + while True: + try: + id_, poi_id_str, spu_id, sku_id, item_city = assigner.take(city) + except queue.Empty: + assigner.finish_city(hd_ind) + log(tag, f'城市 {city} 跑完,尝试接下一个城市') + break + + if not claim_item(id_): + continue + touch_header(hd_ind) + item_done = False + try: + sku_id = '0' + data['variablesStr'] = build_variables_str(poi_id_str, spu_id, sku_id) + req_time = str(int(time.time() * 1000)) + request_url, data = apply_coords(data, url, latitude, longitude, req_time) + mtg_origin = json.loads(headers['mtgsig']) + dfpid = mtg_origin['a3'] + data2 = get_Datatext(data) + openId = headers['openId'] + new_mtgsig = get_sign_new1(request_url, data2, dfpid, mtg_origin, openId, tag=tag) + header_payload = build_mt_headers(headers, new_mtgsig) + try: + # prox = None + req = mt_post(request_url, header_payload, data2, prox) + except Exception as e: + log(tag, f'item={id_} 请求异常: {e}') + bump_stat('fail') + rec = assigner.bump(hd_ind, 'fail') + log(tag, + f'本包计数 ok={rec.get("ok", 0)} fail={rec.get("fail", 0)} 城市剩余={assigner.leftover(city)}') + sleep_interval() + continue + + preview = req.text.replace('\n', ' ') + log(tag, f'item={id_} city={city}/{capital} spu={spu_id} status={req.status_code} {preview}') + + if is_yoda_block(req.text): + bump_stat('yoda') + log(tag, f'[风控] {describe_block(req.text)} backend={BACKEND} loc={loc_source}') + log(tag, '提示: 新号秒死常见原因=刚抓立刻跑 / 坐标代理异地 / 抓包时 mitm 未关') + json_data = json.dumps([request_url, header_payload, data], ensure_ascii=False) + dass = json.dumps([request_url, headers, data2], ensure_ascii=False) + if append_verify_log_once(hd_ind, dass): + log(tag, f'yoda/406,包 {hd_ind} 已记录 verify_log') + update_headers(hd_ind, 418, json_data) + if STOP_PACKAGE_ON_YODA: + assigner.mark_done(hd_ind) + log(tag, f'本包不可用,已成功 {pkg_ok} 条,城市 {city} 已释放,切下一个包') + bump_stat('done_packages') + return 'switch' + sleep_interval() + continue + + if req.status_code == 403: + bump_stat('fail') + update_headers(hd_ind, 403) + assigner.mark_done(hd_ind) + log(tag, f'403,本包不可用,已成功 {pkg_ok} 条,城市 {city} 已释放,切下一个包') + bump_stat('done_packages') + return 'switch' + + if '该商品已下线' in req.text: + log(tag, f'[offline] item={id_} spu={spu_id} 已下线 -> 666,继续') + update_item(id_, 666) + item_done = True + update_headers(hd_ind, 1) + sleep_interval() + continue + + if '"msg":"success"' not in req.text: + bump_stat('fail') + rec = assigner.bump(hd_ind, 'fail') + log(tag, + f'非success 本包计数 ok={rec.get("ok", 0)} fail={rec.get("fail", 0)} 城市剩余={assigner.leftover(city)}') + sleep_interval() + continue + + save_item(id_, json.dumps(req.json(), ensure_ascii=False)) + update_item(id_, 1) + item_done = True + update_headers(hd_ind, 1) + pkg_ok += 1 + bump_stat('ok') + rec = assigner.bump(hd_ind, 'ok') + log( + tag, + f'成功 item={id_} 本包累计={pkg_ok} ' + f'落盘ok={rec.get("ok", 0)} fail={rec.get("fail", 0)} 城市剩余={assigner.leftover(city)}' + ) + sleep_interval() + finally: + if not item_done: + release_item(id_) + except Exception as e: + log(tag, f'包运行异常,切下一个: {e}') + assigner.mark_done(hd_ind) + bump_stat('done_packages') + return 'switch' + finally: + reset_mt_session() + return 'stop' + + +def run_worker(assigner: CityAssigner, slot: int, start_delay: float, proxs: dict, pkg_queue: queue.Queue): + """固定并行数;当前包风控/403/坏数据后从队列领下一个包。""" + if start_delay > 0: + time.sleep(start_delay) + wtag = f'w-{slot}' + while True: + try: + hd = pkg_queue.get_nowait() + except queue.Empty: + log(wtag, '没有剩余包了') + return + hd_ind = hd[0] + if not claim_header(hd_ind): + log(wtag, f'包 {hd_ind} 已被其他电脑领取,换下一个') + continue + assigner.add_live(hd_ind) + log(wtag, f'领取包 {hd_ind} 队列剩余包={pkg_queue.qsize()}') + try: + reason = run_package(hd, assigner, slot, 0, proxs) + finally: + release_header(hd_ind) + if reason == 'switch': + log(wtag, f'包 {hd_ind} 用不了,切换下一个(剩余 {pkg_queue.qsize()})') + continue + if assigner.remaining() > 0: + log(wtag, f'包 {hd_ind} 结束 reason={reason},还有商品 {assigner.remaining()},接下一个包') + continue + log(wtag, f'包 {hd_ind} 结束 reason={reason},本线程退出') + return + + +def run_round(round_no: int, headers, proxs: dict): + """跑一轮:返回 (本轮包数, 商品剩余)。""" + items = get_items() + pkg_count = len(headers) + workers = pkg_count if MAX_WORKERS <= 0 else min(MAX_WORKERS, pkg_count) + known_ids = [hd[0] for hd in headers] + assigner = CityAssigner(items, live_pkg_ids=[], known_pkg_ids=known_ids) + pkg_queue = queue.Queue() + for hd in headers: + pkg_queue.put(hd) + total_items = assigner.remaining() + city_hint = ', '.join(f'{c}:{n}' for c, n in assigner.city_counts().items() if n) + sticky = assigner.dump_bindings() + print(f'[p{PROC_ID}] [round-{round_no}] 城市任务: {city_hint or "无"}') + if sticky: + print(f'[p{PROC_ID}] [round-{round_no}] 沿用包-城市: {sticky}') + + print( + f'[p{PROC_ID}] [round-{round_no}] backend={BACKEND} coord_mode={COORD_MODE} cooldown={COOLDOWN_SEC}s ' + f'并行={workers} 可用包={pkg_count} 商品={total_items} interval={REQUEST_INTERVAL}+0~{INTERVAL_JITTER}s ' + f'进程={PROC_ID}/{PROCESS_COUNT} map={PKG_CITY_MAP_PATH.name} ' + f'一包一城 包废自动切下一个 auto_hd={AUTO_CONTINUE_HD}' + ) + if COOLDOWN_SEC <= 0 and round_no == 1: + print('注意: COOLDOWN_SEC=0,若包是刚抓的极易一摸就死') + if total_items <= 0: + print(f'[p{PROC_ID}] [round-{round_no}] 有包但 drug_detail_list 无待跑商品,跳过本轮') + return pkg_count, 0 + + t0 = time.time() + with ThreadPoolExecutor(max_workers=workers) as pool: + futures = [] + for slot in range(workers): + delay = slot * STAGGER_START + futures.append(pool.submit(run_worker, assigner, slot, delay, proxs, pkg_queue)) + for fu in as_completed(futures): + try: + fu.result() + except Exception as e: + log('main', f'[round-{round_no}] 包线程异常: {e}') + + elapsed = time.time() - t0 + left = assigner.remaining() + print( + f'[p{PROC_ID}] [round-{round_no}] 结束 耗时={elapsed:.1f}s ' + f'成功={_stats["ok"]} 失败={_stats["fail"]} yoda={_stats["yoda"]} ' + f'完成包数={_stats["done_packages"]}/{pkg_count} 未领包={pkg_queue.qsize()} 商品剩余={left}' + ) + return pkg_count, left + + +def main(): + proxs = load_proxs() + if not proxs: + print(f'[p{PROC_ID}] proxs_list 无代理,退出') + return + print( + f'[p{PROC_ID}] 已加载省会代理 {len(proxs)} 个: {", ".join(sorted(proxs.keys()))} ' + f'进程={PROC_ID}/{PROCESS_COUNT} map={PKG_CITY_MAP_PATH.name}' + ) + + t_all = time.time() + round_no = 0 + while True: + round_no += 1 + if PROC_ID == 0: + release_stale_claims() + headers = get_headers() + headers1 = get_headers1() + if not headers1: + items = get_items() + if not items: + print(f'[p{PROC_ID}] [round-{round_no}] 包和商品都空,退出') + break + print( + f'[p{PROC_ID}] [round-{round_no}] 商品还有 {len(items)} 条,' + f'本进程没有可用药店详情包,{PKG_EMPTY_POLL_SEC}s 后再查' + ) + alert_no_package() + time.sleep(PKG_EMPTY_POLL_SEC) + continue + items = get_items() + if not headers: + if items: + print( + f'[p{PROC_ID}] [round-{round_no}] 商品还有 {len(items)} 条,但本进程没有可用包,{HD_RECHECK_SEC}s 后再查') + time.sleep(max(HD_RECHECK_SEC, 5)) + continue + print(f'[p{PROC_ID}] [round-{round_no}] 包和商品都空,退出') + break + + ids = [hd[0] for hd in headers] + print(f'[p{PROC_ID}] [round-{round_no}] 拉到包 {len(headers)} 个: {ids}') + run_round(round_no, headers, proxs) + + if not AUTO_CONTINUE_HD: + break + + if HD_RECHECK_SEC > 0: + print(f'[p{PROC_ID}] [main] 等待 {HD_RECHECK_SEC}s 后检查是否还有任务...') + time.sleep(HD_RECHECK_SEC) + + more = get_headers() + more_items = get_items() + if more and more_items: + print(f'[p{PROC_ID}] [main] 还有 hd={len(more)} 商品={len(more_items)},接下一轮') + continue + if more and not more_items: + print(f'[p{PROC_ID}] [main] 还有包 {len(more)} 个,商品暂时空,继续等') + continue + if more_items and not more: + print(f'[p{PROC_ID}] [main] 商品还有 {len(more_items)} 条,本进程暂无包,继续等') + continue + print(f'[p{PROC_ID}] [main] 复查包和商品都空,全部结束') + break + + print( + f'[p{PROC_ID}] 全程结束 轮次={round_no} 总耗时={time.time() - t_all:.1f}s ' + f'成功={_stats["ok"]} 失败={_stats["fail"]} yoda={_stats["yoda"]} ' + f'完成包数={_stats["done_packages"]}' + ) + + +def worker_main(proc_id: int): + global PROC_ID, PKG_CITY_MAP_PATH + PROC_ID = int(proc_id) + if PROCESS_COUNT > 1: + PKG_CITY_MAP_PATH = SCRIPT_DIR / f'pkg_city_map.p{PROC_ID}.json' + main() + + +def boot(): + n = max(1, int(PROCESS_COUNT)) + if n <= 1: + worker_main(0) + return + print(f'启动 {n} 个进程,每个进程就是一份 run5') + ps = [] + for i in range(n): + p = multiprocessing.Process(target=worker_main, args=(i,), name=f'run5-p{i}') + p.start() + ps.append(p) + for p in ps: + p.join() + + +if __name__ == '__main__': + multiprocessing.freeze_support() + boot()