155 lines
5.6 KiB
Python
155 lines
5.6 KiB
Python
"""JPush 下发。
|
||
|
||
2026-12-03 改版(用户要求):
|
||
1. 推送失败**不重试**,但必须把失败原因写进日志(此前 error 字段一直是空)。
|
||
2. 每一轮扫描,每个用户只发**一条**聚合推送,正文列出本轮全部信号点,
|
||
避免短时间内对同一台设备连推多条(极光频控会延迟甚至丢弃)。
|
||
3. 每条推送带 receipt_token,客户端收到后回执,服务端据此统计到达率。
|
||
未配置凭证时返回 skipped(不阻塞扫描)。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import httpx
|
||
|
||
from ..config import settings
|
||
|
||
API = "https://api.jpush.cn/v3/push"
|
||
|
||
_KIND_LABEL = {
|
||
"long_ignition": "做多起爆点",
|
||
"short_ignition": "做空起爆点",
|
||
"bd_resonance": "卖出(BD共振)",
|
||
"divergence": "量价背离",
|
||
}
|
||
|
||
|
||
def _label(kind: str) -> str:
|
||
return _KIND_LABEL.get(kind, "量价背离")
|
||
|
||
|
||
def _describe(it) -> str:
|
||
"""单条信号的简报:量价背离 RB 30m 12-03 09:30"""
|
||
return f"{_label(it['kind'])} {it['symbol']} {it['interval']} {it['divergence_time'][5:]}"
|
||
|
||
|
||
def build_content(items: list) -> str:
|
||
"""一份推送的正文:列出全部信号点(超过 3 个时省略并标注总数)。"""
|
||
parts = [_describe(it) for it in items]
|
||
if len(parts) == 1:
|
||
it = items[0]
|
||
return f"【{_label(it['kind'])}】{it['symbol']} · {it['interval']} · {it['divergence_time'][5:]}"
|
||
shown = parts[:3]
|
||
more = f"…等 {len(parts)} 个" if len(parts) > 3 else ""
|
||
return f"本轮 {len(parts)} 个信号:" + ";".join(shown) + more
|
||
|
||
|
||
def build_payload(items: list, rids: list[str], batch: dict) -> dict:
|
||
"""一条聚合推送。单个信号保留其 kind(闹钟页显示类型),多个信号用 digest。"""
|
||
if len(items) == 1:
|
||
it = items[0]
|
||
kind = it["kind"]
|
||
else:
|
||
kind = "digest"
|
||
summary = build_content(items)
|
||
extras = {
|
||
"type": "signal_alarm",
|
||
"kind": kind,
|
||
"signal_ids": ",".join(str(it["signal_id"]) for it in items),
|
||
"summary": summary,
|
||
"batch_id": str(batch["id"]),
|
||
"receipt_token": batch["receipt_token"],
|
||
}
|
||
if len(items) == 1:
|
||
# 单条:闹钟页按明细渲染(symbol · interval · 时间),客户端依赖这三项
|
||
it = items[0]
|
||
extras.update({
|
||
"signal_id": str(it["signal_id"]),
|
||
"symbol": it["symbol"],
|
||
"interval": it["interval"],
|
||
"divergence_time": it["divergence_time"],
|
||
})
|
||
return {
|
||
"platform": "android",
|
||
"audience": {"registration_id": rids[:1000]},
|
||
"message": {"title": "玄龙期货", "msg_content": summary, "extras": extras},
|
||
"options": {"time_to_live": 86400},
|
||
}
|
||
|
||
|
||
def send_round_push(items: list, rids: list[str], batch: dict) -> tuple[str, str | None]:
|
||
"""发送一条聚合推送。返回 (status, error)。
|
||
|
||
status ∈ success | failed;失败时 error 记录极光返回体或异常原文——
|
||
按用户要求失败不重试,但必须留下可查的原因。
|
||
"""
|
||
if not settings.jpush_app_key or not settings.jpush_master_secret:
|
||
return "failed", "JPush 凭证未配置"
|
||
payload = build_payload(items, rids, batch)
|
||
try:
|
||
resp = httpx.post(
|
||
API, json=payload,
|
||
auth=(settings.jpush_app_key, settings.jpush_master_secret),
|
||
timeout=10,
|
||
)
|
||
except Exception as exc: # 网络/超时:记录原文
|
||
return "failed", f"{type(exc).__name__}: {exc}"
|
||
if resp.status_code == 200:
|
||
return "success", None
|
||
body = resp.text[:500]
|
||
return "failed", f"HTTP {resp.status_code}: {body}"
|
||
|
||
|
||
def push_test_signal(rids: list[str]) -> dict:
|
||
"""纯测试推送:走真实闹钟链路(自定义消息 + signal_alarm extras),
|
||
不涉及任何行情K线/信号表。文案带【测试】,extras kind=test 供客户端识别。"""
|
||
if not settings.jpush_app_key or not settings.jpush_master_secret or not rids:
|
||
return {"skipped": True}
|
||
from datetime import datetime, timedelta, timezone
|
||
|
||
now = datetime.now(timezone(timedelta(hours=8))).strftime("%Y-%m-%d %H:%M:%S")
|
||
payload = {
|
||
"platform": "android",
|
||
"audience": {"registration_id": rids[:1000]},
|
||
"message": {
|
||
"title": "玄龙期货",
|
||
"msg_content": f"【测试】推送链路测试 {now[5:16]}(收到请忽略)",
|
||
"extras": {
|
||
"type": "signal_alarm",
|
||
"kind": "test",
|
||
"symbol": "测试",
|
||
"interval": "-",
|
||
"divergence_time": now,
|
||
},
|
||
},
|
||
"options": {"time_to_live": 3600},
|
||
}
|
||
try:
|
||
resp = httpx.post(API, json=payload, auth=(settings.jpush_app_key, settings.jpush_master_secret), timeout=8)
|
||
except Exception as e:
|
||
return {"error": str(e)}
|
||
try:
|
||
body = resp.json()
|
||
except Exception:
|
||
body = {"raw": resp.text[:200]}
|
||
return {"http_status": resp.status_code, "body": body}
|
||
|
||
|
||
def push_text(rids: list[str], title: str, body: str) -> None:
|
||
"""纯文本推送(到期提醒等),无深链 extras。"""
|
||
if not settings.jpush_app_key or not rids:
|
||
return
|
||
payload = {
|
||
"platform": "all",
|
||
"audience": {"registration_id": rids[:1000]},
|
||
"notification": {"android": {"alert": body, "title": title}},
|
||
"options": {"time_to_live": 86400},
|
||
}
|
||
try:
|
||
httpx.post(API, json=payload, auth=(settings.jpush_app_key, settings.jpush_master_secret), timeout=8)
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
__all__ = [
|
||
"build_content", "build_payload", "send_round_push", "push_test_signal", "push_text",
|
||
] |