Files
kefu/wechat_rpa/remote_store.py
T
2026-09-29 15:52:07 +08:00

1150 lines
52 KiB
Python

# -*- coding: utf-8 -*-
"""手机远程控制台的数据层。
四张表,全部挂在已有的 ``desktop_accounts`` 上:
mobile_sessions 手机端登录会话。和桌面会话分表存放:桌面会话表上有
"每个账号只能有一个有效会话"的唯一索引,手机登录如果
也写进去,就会把正在值班的电脑顶下线。分表之后两种
令牌也天然不能互相冒用。
desktop_commands 下发给某台电脑的一次性命令(启动 / 停止监听)。
desktop_status 每台电脑随长轮询上报的最新运行状态。
conversation_blacklist 服务端会话黑名单。桌面端本地库降级为缓存,协议引擎和
视觉流程仍只读本地库,离线时照旧生效。
客服电脑在内网、没有入站端口,服务端永远不主动连电脑:命令只是落库,等电脑下一次
长轮询时带走,执行完再回执。
"""
from __future__ import annotations
import json
import re
import secrets
import time
import uuid
from datetime import datetime
from typing import Any, Iterable
from admin_backend import now_text, token_hash
# ── ZYT 菜单权限码(在 ZYT 角色管理里勾选,客服后台只做校验)──────────────
PERM_REMOTE_CONTROL = "wecom_rpa.remote/control"
PERM_REMOTE_ALL = "wecom_rpa.remote/all"
PERM_BLACKLIST_ADD = "wecom_rpa.blacklist/add"
PERM_BLACKLIST_REMOVE = "wecom_rpa.blacklist/remove"
COMMAND_TYPES = {"start_listening": "启动监听", "stop_listening": "停止监听"}
COMMAND_STATUS_LABELS = {
"pending": "已下发,等待电脑领取",
"delivered": "电脑已领取,正在执行",
"succeeded": "已执行",
"failed": "执行失败",
"expired": "电脑未在 10 分钟内确认,已过期",
"superseded": "已被更新的指令取代",
}
FINAL_COMMAND_STATUSES = frozenset({"succeeded", "failed", "expired", "superseded"})
COMMAND_TTL_SECONDS = 10 * 60
MOBILE_SESSION_LIFETIME_SECONDS = 30 * 24 * 60 * 60
# 手机会话每 10 分钟向 ZYT 复核一次身份与权限;复核本身也会让 ZYT 顺延令牌。
MOBILE_IDENTITY_RECHECK_SECONDS = 10 * 60
# 桌面端每 5 秒心跳一次(/desktop/me),30 秒没有心跳就算程序没开。
DEVICE_ONLINE_SECONDS = 30
# 命令通道每次长轮询(最长 25 秒)都会顺带上报状态。
STATUS_FRESH_SECONDS = 90
CAPABILITY_COMMANDS = "commands_v1"
CAPABILITY_BLACKLIST = "blacklist_sync_v1"
STATE_LABELS = {
"running": "监听中",
"connecting": "正在连接企业微信",
"waiting": "等待企业微信",
"verification": "等待企业微信验证",
"recovering": "自动恢复中",
"stopping": "正在停止",
"stopped": "已停止",
"error": "连接失败",
}
TRANSPORT_LABELS = {"visual": "视觉通道", "protocol": "协议通道"}
CONVERSATION_TYPE_LABELS = {
"direct_wechat": "微信联系人",
"direct_wecom": "企业微信联系人",
"group": "群聊",
"application": "应用消息",
"service": "服务通知",
"unknown": "会话",
}
_DEVICE_ID_RE = re.compile(r"^[A-Za-z0-9._:@-]{1,128}$")
_CONTROL_CHARS_RE = re.compile(r"[\x00-\x1f\x7f]")
MAX_SYNC_ITEMS = 500
def _now_epoch() -> int:
return int(time.time())
def _epoch_of(text: Any) -> int | None:
value = str(text or "").strip()
if not value:
return None
try:
return int(datetime.fromisoformat(value.replace("Z", "+00:00")).timestamp())
except ValueError:
return None
def _seconds_since(epoch: int | None, now: int) -> int | None:
return None if epoch is None else max(0, now - int(epoch))
def valid_device_id(value: Any) -> str:
text = str(value or "").strip()
if not _DEVICE_ID_RE.fullmatch(text):
raise ValueError("设备标识不正确")
return text
def clean_key(value: Any, label: str, *, limit: int) -> str:
"""黑名单的账号 / 会话标识:来自企业微信本地库,原样保存,只挡控制字符。"""
text = str(value or "").strip()
if not text or len(text) > limit or _CONTROL_CHARS_RE.search(text):
raise ValueError(f"{label}不正确")
return text
def clean_text(value: Any, *, limit: int) -> str:
return _CONTROL_CHARS_RE.sub(" ", str(value or "")).strip()[:limit]
def _like(value: str) -> str:
escaped = str(value).replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
return f"%{escaped}%"
def account_permissions(account: Any) -> dict[str, bool]:
"""从 desktop_accounts 行里同步下来的 ZYT 权限推出手机端能做什么。
ZYT 对 root 以及"拥有全部菜单"的角色返回 ``*``。remote/all 包含了控制本人
电脑的能力。
"""
try:
raw = json.loads(str(account["zyt_permissions_json"] or "[]"))
except (KeyError, IndexError, TypeError, ValueError):
raw = []
granted = {str(item).strip().lower() for item in raw if str(item).strip()} if isinstance(raw, list) else set()
try:
root = bool(int(account["zyt_root"] or 0)) or "*" in granted
except (KeyError, IndexError, TypeError, ValueError):
root = "*" in granted
try:
known = bool(int(account["zyt_permissions_known"] or 0))
except (KeyError, IndexError, TypeError, ValueError):
known = False
def has(code: str) -> bool:
return root or code in granted
return {
"root": root,
"known": known,
"control": has(PERM_REMOTE_CONTROL) or has(PERM_REMOTE_ALL),
"control_all": has(PERM_REMOTE_ALL),
"blacklist_add": has(PERM_BLACKLIST_ADD),
"blacklist_remove": has(PERM_BLACKLIST_REMOVE),
}
def account_label(account: Any) -> str:
try:
return str(account["nickname"] or account["zyt_sn"] or f"账号{account['id']}")
except (KeyError, IndexError):
return "未知账号"
SCHEMA = """
CREATE TABLE IF NOT EXISTS mobile_sessions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
account_id INTEGER NOT NULL REFERENCES desktop_accounts(id) ON DELETE CASCADE,
token_digest TEXT NOT NULL UNIQUE,
zyt_token_enc TEXT NOT NULL DEFAULT '',
client_name TEXT NOT NULL DEFAULT '',
user_agent TEXT NOT NULL DEFAULT '',
ip_address TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL,
last_used_at TEXT NOT NULL,
last_used_epoch INTEGER NOT NULL DEFAULT 0,
expires_at INTEGER NOT NULL,
identity_checked_at INTEGER NOT NULL DEFAULT 0,
revoked_at TEXT NOT NULL DEFAULT '',
revoke_reason TEXT NOT NULL DEFAULT ''
);
CREATE INDEX IF NOT EXISTS idx_mobile_sessions_account
ON mobile_sessions(account_id, revoked_at, expires_at);
CREATE TABLE IF NOT EXISTS desktop_commands (
id INTEGER PRIMARY KEY AUTOINCREMENT,
command_id TEXT NOT NULL UNIQUE,
account_id INTEGER NOT NULL REFERENCES desktop_accounts(id) ON DELETE CASCADE,
device_id TEXT NOT NULL,
type TEXT NOT NULL CHECK(type IN ('start_listening','stop_listening')),
payload_json TEXT NOT NULL DEFAULT '{}',
status TEXT NOT NULL DEFAULT 'pending'
CHECK(status IN ('pending','delivered','succeeded','failed','expired','superseded')),
created_by_account_id INTEGER,
created_by TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL,
expires_at INTEGER NOT NULL,
delivered_at TEXT NOT NULL DEFAULT '',
delivery_count INTEGER NOT NULL DEFAULT 0,
acked_at TEXT NOT NULL DEFAULT '',
result_json TEXT NOT NULL DEFAULT '{}',
error TEXT NOT NULL DEFAULT ''
);
CREATE INDEX IF NOT EXISTS idx_desktop_commands_target
ON desktop_commands(account_id, device_id, status, id);
CREATE TABLE IF NOT EXISTS desktop_status (
account_id INTEGER NOT NULL REFERENCES desktop_accounts(id) ON DELETE CASCADE,
device_id TEXT NOT NULL,
listening INTEGER NOT NULL DEFAULT 0,
state TEXT NOT NULL DEFAULT '',
transport TEXT NOT NULL DEFAULT '',
wecom_connected INTEGER NOT NULL DEFAULT 0,
pending_count INTEGER NOT NULL DEFAULT 0,
app_version TEXT NOT NULL DEFAULT '',
capabilities_json TEXT NOT NULL DEFAULT '[]',
reported_at TEXT NOT NULL,
reported_epoch INTEGER NOT NULL,
PRIMARY KEY(account_id, device_id)
);
CREATE TABLE IF NOT EXISTS conversation_blacklist (
id INTEGER PRIMARY KEY AUTOINCREMENT,
tenant_id TEXT NOT NULL,
account TEXT NOT NULL,
conversation TEXT NOT NULL,
display_name TEXT NOT NULL DEFAULT '',
account_name TEXT NOT NULL DEFAULT '',
reason TEXT NOT NULL DEFAULT '',
source TEXT NOT NULL DEFAULT 'desktop',
created_by TEXT NOT NULL DEFAULT '',
created_by_account_id INTEGER,
created_at TEXT NOT NULL,
removed_at TEXT NOT NULL DEFAULT '',
removed_by TEXT NOT NULL DEFAULT '',
removed_source TEXT NOT NULL DEFAULT '',
updated_at TEXT NOT NULL,
version INTEGER NOT NULL DEFAULT 0,
UNIQUE(tenant_id, account, conversation)
);
CREATE INDEX IF NOT EXISTS idx_conversation_blacklist_active
ON conversation_blacklist(tenant_id, removed_at, id DESC);
CREATE INDEX IF NOT EXISTS idx_conversation_blacklist_version
ON conversation_blacklist(tenant_id, version);
"""
class RemoteStore:
def __init__(self, database: Any):
self.database = database
def initialize(self) -> None:
with self.database.connect() as db:
db.executescript(SCHEMA)
db.commit()
# ── 账号 ─────────────────────────────────────────────────────────────
def upsert_account(self, identity: dict[str, Any]) -> dict[str, Any]:
"""按 ZYT 身份落到同一条 desktop_accounts,并同步权限;不碰设备与桌面会话。
没用过桌面端的主管第一次登录手机端时会新建一行,这一行在管理端的
「客户端账号」里显示为没有设备。
"""
zyt_user_id = str(identity.get("user_id") or "").strip()
if not zyt_user_id:
raise ValueError("ZYT 用户标识不能为空")
permissions_value = identity.get("permissions")
permissions = sorted(
{str(item).strip() for item in permissions_value if str(item).strip()}
) if isinstance(permissions_value, list) else []
role_ids: list[int] = []
for item in identity.get("role_ids") if isinstance(identity.get("role_ids"), list) else []:
try:
role_ids.append(int(item))
except (TypeError, ValueError):
continue
root = int(bool(identity.get("root")) or "*" in permissions)
known = int(bool(identity.get("permissions_known", isinstance(permissions_value, list))))
mobile = str(identity.get("mobile") or "")
if len(mobile) >= 7:
mobile = f"{mobile[:3]}****{mobile[-4:]}"
stamp = now_text()
tenant_id = self.database._desktop_tenant_id(zyt_user_id)
with self.database.connect() as db:
db.execute("BEGIN IMMEDIATE")
db.execute(
"""INSERT INTO desktop_accounts
(zyt_user_id,tenant_id,zyt_sn,nickname,mobile_masked,avatar,
zyt_root,zyt_role_ids_json,zyt_permissions_json,zyt_permissions_known,
status,created_at,updated_at,last_login_at,last_online_at)
VALUES (?,?,?,?,?,?,?,?,?,?,'active',?,?,'','')
ON CONFLICT(zyt_user_id) DO UPDATE SET
zyt_sn=excluded.zyt_sn,nickname=excluded.nickname,
avatar=excluded.avatar,zyt_root=excluded.zyt_root,
zyt_role_ids_json=excluded.zyt_role_ids_json,
zyt_permissions_json=excluded.zyt_permissions_json,
zyt_permissions_known=excluded.zyt_permissions_known,
updated_at=excluded.updated_at""",
(
zyt_user_id, tenant_id,
str(identity.get("sn") or "")[:128],
str(identity.get("nickname") or "")[:191],
mobile[:32],
str(identity.get("avatar") or "")[:1024],
root,
json.dumps(sorted(set(role_ids))),
json.dumps(permissions, ensure_ascii=False),
known, stamp, stamp,
),
)
account = db.execute(
"SELECT * FROM desktop_accounts WHERE zyt_user_id=?", (zyt_user_id,)
).fetchone()
if account is None or str(account["status"]) != "active":
db.rollback()
raise PermissionError("该账号已被管理端禁用,不能使用手机控制台")
db.commit()
return dict(account)
def account(self, account_id: int) -> dict[str, Any] | None:
row = self.database.desktop_account(int(account_id))
return dict(row) if row is not None else None
# ── 手机会话 ─────────────────────────────────────────────────────────
def create_mobile_session(
self, account_id: int, *, zyt_token: str, client_name: str = "",
user_agent: str = "", ip: str = "",
lifetime: int = MOBILE_SESSION_LIFETIME_SECONDS,
) -> tuple[str, dict[str, Any]]:
import secret_box
token = secrets.token_urlsafe(48)
now = _now_epoch()
stamp = now_text()
expires_at = now + max(300, min(int(lifetime), MOBILE_SESSION_LIFETIME_SECONDS))
encrypted = secret_box.encrypt(str(zyt_token or ""), self.database._secret_key())
with self.database.connect() as db:
db.execute("BEGIN IMMEDIATE")
account = db.execute(
"SELECT * FROM desktop_accounts WHERE id=? AND status='active'", (int(account_id),)
).fetchone()
if account is None:
db.rollback()
raise PermissionError("该账号已被管理端禁用,不能使用手机控制台")
cursor = db.execute(
"""INSERT INTO mobile_sessions
(account_id,token_digest,zyt_token_enc,client_name,user_agent,ip_address,
created_at,last_used_at,last_used_epoch,expires_at,identity_checked_at)
VALUES (?,?,?,?,?,?,?,?,?,?,?)""",
(
int(account_id), token_hash(token), encrypted,
clean_text(client_name, limit=120), clean_text(user_agent, limit=255),
str(ip or "")[:80], stamp, stamp, now, expires_at, now,
),
)
db.execute(
"DELETE FROM mobile_sessions WHERE expires_at<? OR (revoked_at<>'' AND revoked_at<?)",
(now, now_text_days_ago(30)),
)
self.database._audit(
db, None, "mobile.login",
f"account={int(account_id)} session={cursor.lastrowid}", str(ip or ""),
)
db.commit()
return token, {"session_id": int(cursor.lastrowid), "expires_at": expires_at, "created_at": stamp}
def mobile_session(self, token: str) -> dict[str, Any] | None:
if not token:
return None
now = _now_epoch()
with self.database.connect() as db:
row = db.execute(
"""SELECT a.*,s.id AS session_id,s.expires_at AS session_expires_at,
s.created_at AS session_created_at,s.identity_checked_at,
s.last_used_epoch
FROM mobile_sessions s JOIN desktop_accounts a ON a.id=s.account_id
WHERE s.token_digest=? AND s.revoked_at='' AND s.expires_at>=?
AND a.status='active'""",
(token_hash(token), now),
).fetchone()
if row is None:
return None
if now - int(row["last_used_epoch"] or 0) >= 60:
db.execute(
"UPDATE mobile_sessions SET last_used_at=?,last_used_epoch=? WHERE id=?",
(now_text(), now, int(row["session_id"])),
)
db.commit()
return dict(row)
def mobile_zyt_token(self, session_id: int) -> str:
import secret_box
with self.database.connect() as db:
row = db.execute(
"SELECT zyt_token_enc FROM mobile_sessions WHERE id=?", (int(session_id),)
).fetchone()
if row is None or not str(row["zyt_token_enc"] or ""):
return ""
try:
return secret_box.decrypt(str(row["zyt_token_enc"]), self.database._secret_key())
except Exception:
return ""
def mark_identity_checked(self, session_id: int, *, retry_in: int | None = None) -> None:
"""记录复核时间。ZYT 暂时连不上时用 retry_in 让下一次复核提前。"""
checked = _now_epoch()
if retry_in is not None:
checked = checked - MOBILE_IDENTITY_RECHECK_SECONDS + max(10, int(retry_in))
with self.database.connect() as db:
db.execute(
"UPDATE mobile_sessions SET identity_checked_at=? WHERE id=?",
(checked, int(session_id)),
)
db.commit()
def refresh_identity(self, session_id: int, identity: dict[str, Any]) -> None:
account = self.upsert_account(identity)
with self.database.connect() as db:
db.execute(
"UPDATE mobile_sessions SET identity_checked_at=? WHERE id=? AND account_id=?",
(_now_epoch(), int(session_id), int(account["id"])),
)
db.commit()
def revoke_mobile_session(
self, *, token: str = "", session_id: int | None = None, reason: str = "logout",
ip: str = "",
) -> None:
with self.database.connect() as db:
if token:
row = db.execute(
"SELECT id,account_id FROM mobile_sessions WHERE token_digest=?",
(token_hash(token),),
).fetchone()
else:
row = db.execute(
"SELECT id,account_id FROM mobile_sessions WHERE id=?", (int(session_id or 0),)
).fetchone()
if row is None:
return
db.execute(
"""UPDATE mobile_sessions SET revoked_at=?,revoke_reason=?,zyt_token_enc=''
WHERE id=? AND revoked_at=''""",
(now_text(), str(reason)[:40], int(row["id"])),
)
self.database._audit(
db, None, "mobile.logout" if reason == "logout" else "mobile.session.revoke",
f"account={row['account_id']} session={row['id']} reason={reason}", str(ip or ""),
)
db.commit()
def revoke_mobile_sessions_for_account(self, account_id: int, *, reason: str) -> int:
with self.database.connect() as db:
cursor = db.execute(
"""UPDATE mobile_sessions SET revoked_at=?,revoke_reason=?,zyt_token_enc=''
WHERE account_id=? AND revoked_at=''""",
(now_text(), str(reason)[:40], int(account_id)),
)
db.commit()
return int(cursor.rowcount or 0)
def mobile_session_counts(self) -> dict[int, int]:
with self.database.connect() as db:
rows = db.execute(
"""SELECT account_id,COUNT(*) FROM mobile_sessions
WHERE revoked_at='' AND expires_at>=? GROUP BY account_id""",
(_now_epoch(),),
).fetchall()
return {int(row[0]): int(row[1]) for row in rows}
# ── 设备与状态 ───────────────────────────────────────────────────────
def report_status(
self, account_id: int, device_id: str, status: dict[str, Any], *, app_version: str = ""
) -> None:
capabilities = status.get("capabilities")
capabilities = sorted({
clean_text(item, limit=32) for item in capabilities if clean_text(item, limit=32)
})[:16] if isinstance(capabilities, list) else []
try:
pending = max(0, min(int(status.get("pending_count") or 0), 1_000_000))
except (TypeError, ValueError):
pending = 0
now = _now_epoch()
with self.database.connect() as db:
db.execute(
"""INSERT INTO desktop_status
(account_id,device_id,listening,state,transport,wecom_connected,pending_count,
app_version,capabilities_json,reported_at,reported_epoch)
VALUES (?,?,?,?,?,?,?,?,?,?,?)
ON CONFLICT(account_id,device_id) DO UPDATE SET
listening=excluded.listening,state=excluded.state,
transport=excluded.transport,wecom_connected=excluded.wecom_connected,
pending_count=excluded.pending_count,app_version=excluded.app_version,
capabilities_json=excluded.capabilities_json,
reported_at=excluded.reported_at,reported_epoch=excluded.reported_epoch""",
(
int(account_id), valid_device_id(device_id),
int(bool(status.get("listening"))),
clean_text(status.get("state"), limit=32),
clean_text(status.get("transport"), limit=16),
int(bool(status.get("wecom_connected"))),
pending,
clean_text(status.get("app_version") or app_version, limit=64),
json.dumps(capabilities), now_text(), now,
),
)
db.commit()
def devices(self, account_id: int, *, device_id: str = "") -> list[dict[str, Any]]:
now = _now_epoch()
params: list[Any] = [now, int(account_id)]
extra = ""
if device_id:
extra = " AND d.device_id=?"
params.append(valid_device_id(device_id))
with self.database.connect() as db:
rows = db.execute(
f"""SELECT d.id AS device_row_id,d.device_id,d.device_name,d.app_version,
d.last_seen_at,
(SELECT COUNT(*) FROM desktop_sessions s
WHERE s.device_row_id=d.id AND s.revoked_at=''
AND s.expires_at>=?) AS active_sessions,
st.listening,st.state,st.transport,st.wecom_connected,
st.pending_count,st.app_version AS status_app_version,
st.capabilities_json,st.reported_at,st.reported_epoch
FROM desktop_devices d
LEFT JOIN desktop_status st
ON st.account_id=d.account_id AND st.device_id=d.device_id
WHERE d.account_id=? AND d.revoked_at=''{extra}
ORDER BY d.last_seen_at DESC,d.id DESC""",
tuple(params),
).fetchall()
commands = {}
for row in rows:
latest = db.execute(
"""SELECT * FROM desktop_commands WHERE account_id=? AND device_id=?
ORDER BY id DESC LIMIT 1""",
(int(account_id), str(row["device_id"])),
).fetchone()
if latest is not None:
commands[str(row["device_id"])] = self._public_command(latest, now)
return [self._public_device(row, commands.get(str(row["device_id"])), now) for row in rows]
def device(self, account_id: int, device_id: str) -> dict[str, Any] | None:
items = self.devices(account_id, device_id=device_id)
return items[0] if items else None
@staticmethod
def _public_device(row: Any, command: dict[str, Any] | None, now: int) -> dict[str, Any]:
seen_epoch = _epoch_of(row["last_seen_at"])
seen_seconds = _seconds_since(seen_epoch, now)
session_active = int(row["active_sessions"] or 0) > 0
online = bool(session_active and seen_seconds is not None and seen_seconds <= DEVICE_ONLINE_SECONDS)
status = None
remote_capable = False
blacklist_sync = False
if row["reported_epoch"] is not None:
try:
capabilities = set(json.loads(str(row["capabilities_json"] or "[]")))
except (TypeError, ValueError):
capabilities = set()
reported_seconds = _seconds_since(int(row["reported_epoch"]), now)
fresh = reported_seconds is not None and reported_seconds <= STATUS_FRESH_SECONDS
same_build = str(row["status_app_version"] or "") == str(row["app_version"] or "")
# 同一台电脑降级回旧版本时,旧的能力声明不能继续算数。
remote_capable = CAPABILITY_COMMANDS in capabilities and (fresh or same_build)
blacklist_sync = CAPABILITY_BLACKLIST in capabilities and (fresh or same_build)
state = str(row["state"] or "")
transport = str(row["transport"] or "")
status = {
"listening": bool(row["listening"]),
"state": state,
"state_label": STATE_LABELS.get(state, state or "未知"),
"transport": transport,
"transport_label": TRANSPORT_LABELS.get(transport, transport or "未知"),
"wecom_connected": bool(row["wecom_connected"]),
"pending_count": int(row["pending_count"] or 0),
"reported_at": str(row["reported_at"] or ""),
"reported_seconds": reported_seconds,
"fresh": fresh,
}
return {
"device_id": str(row["device_id"]),
"device_name": str(row["device_name"] or ""),
"app_version": str(row["app_version"] or ""),
"online": online,
"session_active": session_active,
"last_seen_at": str(row["last_seen_at"] or ""),
"last_seen_seconds": seen_seconds,
"remote_capable": remote_capable,
"blacklist_sync": blacklist_sync,
"status": status,
"last_command": command,
}
def accounts_overview(self, query: str = "", limit: int = 100) -> list[dict[str, Any]]:
"""全部客服电脑的概况,只给有 remote/all 权限的人看。"""
params: list[Any] = []
where = "WHERE a.status='active'"
needle = str(query or "").strip()
if needle:
where += " AND (a.nickname LIKE ? ESCAPE '\\' OR a.zyt_sn LIKE ? ESCAPE '\\')"
params.extend([_like(needle), _like(needle)])
params.append(max(1, min(int(limit or 100), 300)))
with self.database.connect() as db:
rows = db.execute(
f"""SELECT a.id,a.nickname,a.zyt_sn,a.last_online_at,
(SELECT COUNT(*) FROM desktop_devices d
WHERE d.account_id=a.id AND d.revoked_at='') AS device_count
FROM desktop_accounts a {where}
ORDER BY a.last_online_at DESC,a.id DESC LIMIT ?""",
tuple(params),
).fetchall()
result = []
for row in rows:
devices = self.devices(int(row["id"])) if int(row["device_count"] or 0) else []
result.append({
"id": int(row["id"]),
"nickname": str(row["nickname"] or ""),
"sn": str(row["zyt_sn"] or ""),
"device_count": len(devices),
"online": any(item["online"] for item in devices),
"listening": any(
item["online"] and item["status"] and item["status"]["listening"]
for item in devices
),
"last_online_at": str(row["last_online_at"] or ""),
})
return result
# ── 命令 ─────────────────────────────────────────────────────────────
@staticmethod
def _public_command(row: Any, now: int | None = None) -> dict[str, Any]:
now = _now_epoch() if now is None else now
status = str(row["status"])
if status in {"pending", "delivered"} and int(row["expires_at"]) < now:
status = "expired"
try:
result = json.loads(str(row["result_json"] or "{}"))
except (TypeError, ValueError):
result = {}
return {
"id": str(row["command_id"]),
"type": str(row["type"]),
"type_label": COMMAND_TYPES.get(str(row["type"]), str(row["type"])),
"device_id": str(row["device_id"]),
"status": status,
"status_label": COMMAND_STATUS_LABELS.get(status, status),
"final": status in FINAL_COMMAND_STATUSES,
"created_at": str(row["created_at"]),
"created_by": str(row["created_by"] or ""),
"delivered_at": str(row["delivered_at"] or ""),
"acked_at": str(row["acked_at"] or ""),
"expires_at": int(row["expires_at"]),
"result": result if isinstance(result, dict) else {},
"error": str(row["error"] or ""),
}
def create_command(
self, *, account_id: int, device_id: str, command_type: str,
actor_account_id: int, actor_label: str, ip: str,
) -> dict[str, Any]:
if command_type not in COMMAND_TYPES:
raise ValueError("不支持的指令")
device_id = valid_device_id(device_id)
now = _now_epoch()
stamp = now_text()
command_id = uuid.uuid4().hex
with self.database.connect() as db:
db.execute("BEGIN IMMEDIATE")
if db.execute(
"""SELECT 1 FROM desktop_devices
WHERE account_id=? AND device_id=? AND revoked_at=''""",
(int(account_id), device_id),
).fetchone() is None:
db.rollback()
raise LookupError("电脑不存在或已被管理端下线")
# 还没被电脑领走的旧指令直接作废:连点"停止、启动"时,电脑只该执行最后一次。
# 已经领走的正在执行,不能撤回,交给电脑按顺序执行。
db.execute(
"""UPDATE desktop_commands SET status='superseded',acked_at=?
WHERE account_id=? AND device_id=? AND status='pending'""",
(stamp, int(account_id), device_id),
)
db.execute(
"""INSERT INTO desktop_commands
(command_id,account_id,device_id,type,payload_json,status,
created_by_account_id,created_by,created_at,expires_at)
VALUES (?,?,?,?,?,'pending',?,?,?,?)""",
(
command_id, int(account_id), device_id, command_type, "{}",
int(actor_account_id), clean_text(actor_label, limit=120), stamp,
now + COMMAND_TTL_SECONDS,
),
)
self.database._audit(
db, None, "remote.command.create",
f"command={command_id} account={int(account_id)} device={device_id[:64]} "
f"type={command_type} by_account={int(actor_account_id)}",
str(ip or ""),
)
db.commit()
row = db.execute(
"SELECT * FROM desktop_commands WHERE command_id=?", (command_id,)
).fetchone()
return self._public_command(row, now)
def command(self, command_id: str) -> dict[str, Any] | None:
with self.database.connect() as db:
row = db.execute(
"SELECT * FROM desktop_commands WHERE command_id=?", (str(command_id or ""),)
).fetchone()
if row is None:
return None
payload = self._public_command(row)
payload["account_id"] = int(row["account_id"])
return payload
def has_open_commands(self, account_id: int, device_id: str) -> bool:
with self.database.connect() as db:
return db.execute(
"""SELECT 1 FROM desktop_commands
WHERE account_id=? AND device_id=? AND status IN ('pending','delivered')
LIMIT 1""",
(int(account_id), str(device_id)),
).fetchone() is not None
def take_commands(self, account_id: int, device_id: str) -> list[dict[str, Any]]:
"""把待执行指令交给电脑。
领取不等于完成:电脑回执之前每次轮询都会再拿到一次,由电脑按指令 id 去重。
这样长轮询的响应在路上丢了,指令也不会跟着丢。
"""
if not self.has_open_commands(account_id, device_id):
return []
now = _now_epoch()
stamp = now_text()
with self.database.connect() as db:
db.execute("BEGIN IMMEDIATE")
db.execute(
"""UPDATE desktop_commands SET status='expired'
WHERE account_id=? AND device_id=? AND status IN ('pending','delivered')
AND expires_at<?""",
(int(account_id), str(device_id), now),
)
rows = db.execute(
"""SELECT * FROM desktop_commands
WHERE account_id=? AND device_id=? AND status IN ('pending','delivered')
ORDER BY id LIMIT 10""",
(int(account_id), str(device_id)),
).fetchall()
for row in rows:
db.execute(
"""UPDATE desktop_commands SET status='delivered',
delivered_at=CASE WHEN delivered_at='' THEN ? ELSE delivered_at END,
delivery_count=delivery_count+1
WHERE id=?""",
(stamp, int(row["id"])),
)
db.commit()
return [
{
"id": str(row["command_id"]),
"type": str(row["type"]),
"payload": {},
"created_at": str(row["created_at"]),
"created_by": str(row["created_by"] or ""),
"expires_at": int(row["expires_at"]),
}
for row in rows
]
def ack_command(
self, *, account_id: int, device_id: str, command_id: str, ok: bool,
result: dict[str, Any] | None, error: str, ip: str,
) -> dict[str, Any]:
stamp = now_text()
now = _now_epoch()
with self.database.connect() as db:
db.execute("BEGIN IMMEDIATE")
row = db.execute(
"""SELECT * FROM desktop_commands
WHERE command_id=? AND account_id=? AND device_id=?""",
(str(command_id or ""), int(account_id), str(device_id)),
).fetchone()
if row is None:
db.rollback()
raise LookupError("指令不存在")
status = str(row["status"])
if status in {"succeeded", "failed"}:
db.rollback()
return self._public_command(row, now)
if status in {"pending", "delivered"} and int(row["expires_at"]) >= now:
status = "succeeded" if ok else "failed"
elif status in {"pending", "delivered"}:
status = "expired"
safe_result = result if isinstance(result, dict) else {}
encoded = json.dumps(safe_result, ensure_ascii=False)[:4000]
db.execute(
"""UPDATE desktop_commands SET status=?,acked_at=?,result_json=?,error=?
WHERE id=?""",
(status, stamp, encoded, clean_text(error, limit=500), int(row["id"])),
)
self.database._audit(
db, None, "remote.command.ack",
f"command={row['command_id']} account={int(account_id)} status={status}",
str(ip or ""),
)
db.commit()
row = db.execute("SELECT * FROM desktop_commands WHERE id=?", (int(row["id"]),)).fetchone()
return self._public_command(row, now)
# ── 黑名单 ───────────────────────────────────────────────────────────
@staticmethod
def _public_entry(row: Any) -> dict[str, Any]:
return {
"account": str(row["account"]),
"account_name": str(row["account_name"] or ""),
"conversation": str(row["conversation"]),
"name": str(row["display_name"] or ""),
"reason": str(row["reason"] or ""),
"source": str(row["source"] or ""),
"created_by": str(row["created_by"] or ""),
"created_at": str(row["created_at"] or ""),
}
@staticmethod
def _version(db: Any, tenant_id: str) -> int:
return int(db.execute(
"SELECT COALESCE(MAX(version),0) FROM conversation_blacklist WHERE tenant_id=?",
(tenant_id,),
).fetchone()[0])
def blacklist_version(self, tenant_id: str) -> int:
with self.database.connect() as db:
return self._version(db, str(tenant_id))
def blacklist(self, tenant_id: str) -> tuple[int, list[dict[str, Any]]]:
with self.database.connect() as db:
rows = db.execute(
"""SELECT * FROM conversation_blacklist WHERE tenant_id=? AND removed_at=''
ORDER BY account,conversation""",
(str(tenant_id),),
).fetchall()
version = self._version(db, str(tenant_id))
return version, [self._public_entry(row) for row in rows]
@staticmethod
def _archive_names(db: Any, tenant_id: str, account: str, conversation: str) -> tuple[str, str]:
"""补上会话名和企微账号名;归档表不存在或没有这条会话时返回空串。"""
try:
row = db.execute(
"""SELECT c.name,a.display_name FROM archive_conversation c
JOIN archive_source_account a ON a.id=c.source_account_id
WHERE c.tenant_id=? AND a.external_account_id=? AND c.external_id=?
LIMIT 1""",
(tenant_id, account, conversation),
).fetchone()
except Exception:
return "", ""
if row is None:
return "", ""
return str(row[0] or ""), str(row[1] or "")
def _add_entry(
self, db: Any, tenant_id: str, item: dict[str, Any], *, source: str,
actor_label: str, actor_account_id: int | None, version: int,
) -> tuple[dict[str, Any], bool]:
account = clean_key(item.get("account"), "企业微信账号", limit=191)
conversation = clean_key(item.get("conversation"), "会话", limit=512)
name = clean_text(item.get("name"), limit=191)
account_name = clean_text(item.get("account_name"), limit=191)
reason = clean_text(item.get("reason"), limit=200)
if not name or not account_name:
archive_name, archive_account = self._archive_names(db, tenant_id, account, conversation)
name = name or archive_name
account_name = account_name or archive_account
stamp = now_text()
row = db.execute(
"""SELECT * FROM conversation_blacklist
WHERE tenant_id=? AND account=? AND conversation=?""",
(tenant_id, account, conversation),
).fetchone()
if row is not None and not str(row["removed_at"] or ""):
changed = (
(name and name != row["display_name"])
or (account_name and account_name != row["account_name"])
or (reason and reason != row["reason"])
)
if changed:
db.execute(
"""UPDATE conversation_blacklist SET
display_name=CASE WHEN ?<>'' THEN ? ELSE display_name END,
account_name=CASE WHEN ?<>'' THEN ? ELSE account_name END,
reason=CASE WHEN ?<>'' THEN ? ELSE reason END,
updated_at=?,version=? WHERE id=?""",
(name, name, account_name, account_name, reason, reason, stamp, version,
int(row["id"])),
)
fresh = db.execute("SELECT * FROM conversation_blacklist WHERE id=?", (int(row["id"]),)).fetchone()
return self._public_entry(fresh), bool(changed)
if row is not None:
db.execute(
"""UPDATE conversation_blacklist SET display_name=?,account_name=?,reason=?,
source=?,created_by=?,created_by_account_id=?,created_at=?,
removed_at='',removed_by='',removed_source='',updated_at=?,version=?
WHERE id=?""",
(name or row["display_name"], account_name or row["account_name"], reason,
source, clean_text(actor_label, limit=120), actor_account_id, stamp, stamp,
version, int(row["id"])),
)
fresh = db.execute("SELECT * FROM conversation_blacklist WHERE id=?", (int(row["id"]),)).fetchone()
return self._public_entry(fresh), True
cursor = db.execute(
"""INSERT INTO conversation_blacklist
(tenant_id,account,conversation,display_name,account_name,reason,source,
created_by,created_by_account_id,created_at,updated_at,version)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?)""",
(tenant_id, account, conversation, name, account_name, reason, source,
clean_text(actor_label, limit=120), actor_account_id, stamp, stamp, version),
)
fresh = db.execute("SELECT * FROM conversation_blacklist WHERE id=?", (int(cursor.lastrowid),)).fetchone()
return self._public_entry(fresh), True
def add_blacklist(
self, tenant_id: str, item: dict[str, Any], *, source: str, actor_label: str,
actor_account_id: int | None, ip: str,
) -> tuple[dict[str, Any], int]:
tenant_id = str(tenant_id)
with self.database.connect() as db:
db.execute("BEGIN IMMEDIATE")
version = self._version(db, tenant_id) + 1
entry, changed = self._add_entry(
db, tenant_id, item, source=source, actor_label=actor_label,
actor_account_id=actor_account_id, version=version,
)
if changed:
self.database._audit(
db, None, "blacklist.add",
f"tenant={tenant_id} account={entry['account'][:64]} "
f"conversation={entry['conversation'][:120]} source={source} "
f"by={clean_text(actor_label, limit=60)}",
str(ip or ""),
)
db.commit()
else:
db.rollback()
current = self._version(db, tenant_id)
return entry, current
def remove_blacklist(
self, tenant_id: str, account: str, conversation: str, *, source: str,
actor_label: str, ip: str,
) -> int:
tenant_id = str(tenant_id)
account = clean_key(account, "企业微信账号", limit=191)
conversation = clean_key(conversation, "会话", limit=512)
with self.database.connect() as db:
db.execute("BEGIN IMMEDIATE")
row = db.execute(
"""SELECT id FROM conversation_blacklist
WHERE tenant_id=? AND account=? AND conversation=? AND removed_at=''""",
(tenant_id, account, conversation),
).fetchone()
if row is None:
db.rollback()
raise LookupError("该会话不在黑名单中")
version = self._version(db, tenant_id) + 1
stamp = now_text()
db.execute(
"""UPDATE conversation_blacklist SET removed_at=?,removed_by=?,removed_source=?,
updated_at=?,version=? WHERE id=?""",
(stamp, clean_text(actor_label, limit=120), source, stamp, version, int(row["id"])),
)
self.database._audit(
db, None, "blacklist.remove",
f"tenant={tenant_id} account={account[:64]} conversation={conversation[:120]} "
f"source={source} by={clean_text(actor_label, limit=60)}",
str(ip or ""),
)
db.commit()
return version
def sync_desktop_blacklist(
self, tenant_id: str, adds: Iterable[dict[str, Any]], *, actor_label: str,
actor_account_id: int | None, ip: str,
) -> tuple[int, list[dict[str, Any]], list[dict[str, Any]]]:
"""桌面端补传本地新增(含升级前的历史条目),然后拿回全量。"""
tenant_id = str(tenant_id)
items = list(adds or [])[:MAX_SYNC_ITEMS]
rejected: list[dict[str, Any]] = []
added = 0
with self.database.connect() as db:
db.execute("BEGIN IMMEDIATE")
version = self._version(db, tenant_id) + 1
for item in items:
if not isinstance(item, dict):
continue
try:
_entry, changed = self._add_entry(
db, tenant_id, item, source="desktop", actor_label=actor_label,
actor_account_id=actor_account_id, version=version,
)
except ValueError as exc:
rejected.append({
"account": str(item.get("account") or "")[:191],
"conversation": str(item.get("conversation") or "")[:512],
"error": str(exc),
})
continue
added += int(changed)
if added:
self.database._audit(
db, None, "blacklist.sync",
f"tenant={tenant_id} added={added} by={clean_text(actor_label, limit=60)}",
str(ip or ""),
)
db.commit()
else:
db.rollback()
version, entries = self.blacklist(tenant_id)
return version, entries, rejected
# ── 会话 ─────────────────────────────────────────────────────────────
def conversations(
self, tenant_id: str, *, query: str = "", scope: str = "all", cursor: str = "",
limit: int = 30,
) -> dict[str, Any]:
"""手机端会话列表。只给名称、类型、最近时间和黑名单状态,不出聊天正文。"""
tenant_id = str(tenant_id)
limit = max(1, min(int(limit or 30), 100))
needle = str(query or "").strip()[:100]
with self.database.connect() as db:
blocked_total = int(db.execute(
"SELECT COUNT(*) FROM conversation_blacklist WHERE tenant_id=? AND removed_at=''",
(tenant_id,),
).fetchone()[0])
if scope == "blocked":
params: list[Any] = [tenant_id]
where = "b.tenant_id=? AND b.removed_at=''"
if needle:
where += (" AND (b.display_name LIKE ? ESCAPE '\\' OR b.conversation LIKE ? ESCAPE '\\'"
" OR b.account_name LIKE ? ESCAPE '\\')")
params.extend([_like(needle)] * 3)
if cursor:
try:
where += " AND b.id<?"
params.append(int(cursor))
except ValueError as exc:
raise ValueError("分页游标不正确") from exc
params.append(limit + 1)
rows = db.execute(
f"""SELECT b.* FROM conversation_blacklist b WHERE {where}
ORDER BY b.id DESC LIMIT ?""",
tuple(params),
).fetchall()
has_more = len(rows) > limit
rows = rows[:limit]
items = []
for row in rows:
archive_name, archive_account = ("", "")
if not row["display_name"] or not row["account_name"]:
archive_name, archive_account = self._archive_names(
db, tenant_id, str(row["account"]), str(row["conversation"])
)
conversation = str(row["conversation"])
kind = _conversation_kind(conversation)
items.append({
"account": str(row["account"]),
"account_name": str(row["account_name"] or archive_account or ""),
"conversation": conversation,
"name": str(row["display_name"] or archive_name or conversation),
"type": kind,
"type_label": CONVERSATION_TYPE_LABELS.get(kind, "会话"),
"last_message_at": "",
"blocked": True,
"blacklist": self._public_entry(row),
})
next_cursor = str(rows[-1]["id"]) if has_more and rows else ""
return {"items": items, "next_cursor": next_cursor, "has_more": has_more,
"blocked_total": blocked_total}
params = [tenant_id]
where = "c.tenant_id=?"
if needle:
where += " AND (c.name LIKE ? ESCAPE '\\' OR c.external_id LIKE ? ESCAPE '\\')"
params.extend([_like(needle), _like(needle)])
if cursor:
try:
cursor_time, cursor_id = cursor.split("|", 1)
except ValueError as exc:
raise ValueError("分页游标不正确") from exc
where += " AND (c.last_message_at,c.id)<(?,?)"
params.extend([cursor_time, cursor_id])
params.append(limit + 1)
try:
rows = db.execute(
f"""SELECT c.id,c.external_id,c.name,c.conversation_type,c.last_message_at,
a.external_account_id,a.display_name AS account_display_name,
b.id AS blacklist_id,b.account,b.conversation,b.display_name,
b.account_name,b.reason,b.source,b.created_by,b.created_at
FROM archive_conversation c
JOIN archive_source_account a ON a.id=c.source_account_id
LEFT JOIN conversation_blacklist b
ON b.tenant_id=c.tenant_id AND b.account=a.external_account_id
AND b.conversation=c.external_id AND b.removed_at=''
WHERE {where}
ORDER BY c.last_message_at DESC,c.id DESC LIMIT ?""",
tuple(params),
).fetchall()
except Exception as exc:
if "no such table" in str(exc):
rows = []
else:
raise
has_more = len(rows) > limit
rows = rows[:limit]
items = []
for row in rows:
kind = str(row["conversation_type"] or "unknown")
items.append({
"account": str(row["external_account_id"]),
"account_name": str(row["account_display_name"] or ""),
"conversation": str(row["external_id"]),
"name": str(row["name"] or row["external_id"]),
"type": kind,
"type_label": CONVERSATION_TYPE_LABELS.get(kind, "会话"),
"last_message_at": str(row["last_message_at"] or ""),
"blocked": row["blacklist_id"] is not None,
"blacklist": self._public_entry(row) if row["blacklist_id"] is not None else None,
})
next_cursor = f"{rows[-1]['last_message_at']}|{rows[-1]['id']}" if has_more and rows else ""
return {"items": items, "next_cursor": next_cursor, "has_more": has_more,
"blocked_total": blocked_total}
def _conversation_kind(external_id: str) -> str:
prefix = str(external_id or "").split(":", 1)[0].upper()
return {
"M": "direct_wechat", "S": "direct_wecom", "R": "group",
"Y": "application", "O": "service",
}.get(prefix, "unknown")
def now_text_days_ago(days: int) -> str:
from datetime import timedelta
return (datetime.now().astimezone() - timedelta(days=int(days))).isoformat(timespec="seconds")