日报Cookie检测改为真实API验证+ALF过期时间双重判断, 失效自动标记

This commit is contained in:
2026-04-17 09:13:58 +08:00
parent dccfae5227
commit 0d044ef511

View File

@@ -730,7 +730,8 @@ async def _build_daily_report() -> str:
if msg:
rank_details.append({"name": name, "topic": topic, "message": msg})
# 4. Cookie 过期时间检测(从 ALF 字段解析)
# 4. Cookie 真实有效性检测(调用微博 API 验证)+ ALF 过期时间
import httpx as _httpx
cookie_expiry = []
all_accounts_result = await session.execute(
select(Account.id, Account.remark, Account.weibo_user_id,
@@ -739,28 +740,68 @@ async def _build_daily_report() -> str:
)
key = derive_key(shared_settings.COOKIE_ENCRYPTION_KEY)
for acc_row in all_accounts_result.all():
acc_id, remark, uid, enc_cookies, iv, status = acc_row
acc_id, remark, uid, enc_cookies, iv, acc_status = acc_row
name = remark or uid
try:
cookie_str = decrypt_cookie(enc_cookies, iv, key)
cookie_dict = {}
alf = ""
for pair in cookie_str.split(";"):
pair = pair.strip()
if pair.startswith("ALF="):
alf = pair.split("=", 1)[1].strip()
break
if "=" in pair:
k, v = pair.split("=", 1)
cookie_dict[k.strip()] = v.strip()
if k.strip() == "ALF":
alf = v.strip()
# ALF 过期时间
remain_days = -1
expire_str = "未知"
if alf and alf.isdigit():
expire_dt = datetime.fromtimestamp(int(alf))
remain_days = (expire_dt - now).days
cookie_expiry.append({
"name": name,
"expire": expire_dt.strftime("%m-%d"),
"remain": remain_days,
})
else:
cookie_expiry.append({"name": name, "expire": "未知", "remain": -1})
expire_str = expire_dt.strftime("%m-%d")
# 真实 API 验证
real_valid = False
try:
async with _httpx.AsyncClient(timeout=10, follow_redirects=True) as hc:
vresp = await hc.get(
"https://weibo.com/ajax/side/cards",
params={"count": "1"},
headers=WEIBO_HEADERS,
cookies=cookie_dict,
)
try:
vdata = vresp.json()
real_valid = vdata.get("ok") == 1
except Exception:
real_valid = False
except Exception:
real_valid = False
cookie_expiry.append({
"name": name,
"expire": expire_str,
"remain": remain_days,
"real_valid": real_valid,
"acc_id": str(acc_id),
})
# 如果 API 验证失效,更新数据库状态
if not real_valid and acc_status == "active":
acc_obj = await session.get(Account, acc_id)
if acc_obj:
acc_obj.status = "invalid_cookie"
logger.warning(f"日报检测: {name} Cookie 实际已失效,已标记")
except Exception:
cookie_expiry.append({"name": name, "expire": "解密失败", "remain": -1})
cookie_expiry.append({
"name": name, "expire": "解密失败", "remain": -1,
"real_valid": False, "acc_id": str(acc_id),
})
await session.commit()
finally:
await eng.dispose()
@@ -797,21 +838,28 @@ async def _build_daily_report() -> str:
lines.append(f" {r['name']} - {r['topic']}: {r['message']}")
if cookie_expiry:
lines += ["", "🍪 Cookie 有效期"]
lines += ["", "🍪 Cookie 状态"]
expiring_soon = []
invalid_names = []
for ce in cookie_expiry:
remain = ce["remain"]
if remain < 0:
lines.append(f" ⚠️ {ce['name']}: {ce['expire']}")
elif remain <= 3:
lines.append(f" 🔴 {ce['name']}: {ce['expire']} (剩 {remain} 天,即将过期!)")
valid = ce.get("real_valid", False)
if not valid:
lines.append(f"{ce['name']}: 已失效 (ALF: {ce['expire']})")
invalid_names.append(ce["name"])
elif remain >= 0 and remain <= 3:
lines.append(f" 🔴 {ce['name']}: 有效 · {ce['expire']}到期 (剩 {remain} 天)")
expiring_soon.append(ce["name"])
elif remain <= 7:
lines.append(f" 🟡 {ce['name']}: {ce['expire']} (剩 {remain} 天)")
elif remain >= 0 and remain <= 7:
lines.append(f" 🟡 {ce['name']}: 有效 · {ce['expire']}到期 (剩 {remain} 天)")
elif remain > 7:
lines.append(f" 🟢 {ce['name']}: 有效 · {ce['expire']}到期 (剩 {remain} 天)")
else:
lines.append(f" 🟢 {ce['name']}: {ce['expire']} (剩 {remain} 天)")
if expiring_soon:
lines.append(f" ⚠️ 请尽快重新扫码: {', '.join(expiring_soon)}")
lines.append(f" ⚠️ {ce['name']}: {'有效' if valid else '未知'} · 过期时间未知")
if invalid_names:
lines.append(f" 🚨 请重新扫码: {', '.join(invalid_names)}")
elif expiring_soon:
lines.append(f" ⚠️ 即将过期,请尽快重新扫码: {', '.join(expiring_soon)}")
if total_logs == 0:
lines += ["", "💤 今日暂无签到记录"]