Files
xieyi-weixin-/conversation_blacklist.py
T
2026-09-28 10:02:07 +08:00

98 lines
4.5 KiB
Python

"""Durable account-scoped outbound deny list shared by desktop engines."""
from contextlib import closing
from datetime import datetime
import sqlite3
from pathlib import Path
from runtime_paths import application_data_dir
BLOCKED_REASON = '该会话已加入黑名单,系统禁止发送消息'
def _path(root):
return (Path(root or application_data_dir()) / 'conversation_blacklist.sqlite3').resolve()
def entries(root=None):
path = _path(root)
if not path.exists():
return set()
with closing(sqlite3.connect(path.as_uri() + '?mode=ro', uri=True, timeout=2)) as db:
return {(str(a), str(c)) for a, c in db.execute('SELECT account,conversation FROM blocked')}
def list_entries(root=None):
"""Read all accounts, including entries absent from the current message list."""
path = _path(root)
if not path.exists():
return []
with closing(sqlite3.connect(path.as_uri() + '?mode=ro', uri=True, timeout=2)) as db:
db.row_factory = sqlite3.Row
columns = {row[1] for row in db.execute('PRAGMA table_info(blocked)')}
fields = ['account', 'conversation'] + [
name if name in columns else "'' AS " + name
for name in ('name', 'account_name', 'created_at')
]
return [dict(row) for row in db.execute(
'SELECT ' + ','.join(fields) + ' FROM blocked ORDER BY account,conversation')]
def _initialize(db):
db.execute('CREATE TABLE IF NOT EXISTS blocked (account TEXT NOT NULL, conversation TEXT NOT NULL, PRIMARY KEY(account,conversation))')
columns = {row[1] for row in db.execute('PRAGMA table_info(blocked)')}
for name in ('name', 'account_name', 'created_at'):
if name not in columns:
db.execute("ALTER TABLE blocked ADD COLUMN " + name + " TEXT NOT NULL DEFAULT ''")
def set_blocked(account, conversation, blocked, *, root=None, name='', account_name=''):
account, conversation = str(account or '').strip(), str(conversation or '').strip()
if not account or not conversation or type(blocked) is not bool:
raise ValueError('请选择有效账号和会话')
path = _path(root)
path.parent.mkdir(parents=True, exist_ok=True)
with closing(sqlite3.connect(path, timeout=5)) as db, db:
_initialize(db)
if blocked:
db.execute("""INSERT INTO blocked (account,conversation,name,account_name,created_at)
VALUES (?,?,?,?,?) ON CONFLICT(account,conversation) DO UPDATE SET
name=CASE WHEN excluded.name<>'' THEN excluded.name ELSE blocked.name END,
account_name=CASE WHEN excluded.account_name<>'' THEN excluded.account_name ELSE blocked.account_name END""",
(account, conversation, str(name or ''), str(account_name or ''), datetime.now().strftime('%Y-%m-%d %H:%M:%S')))
else:
db.execute('DELETE FROM blocked WHERE account=? AND conversation=?', (account, conversation))
def remove_entries(items, *, root=None):
"""Validate the whole selection, then remove exact account/conversation pairs atomically."""
if not isinstance(items, list) or not items:
raise ValueError('请先勾选需要移除的会话')
pairs = set()
for item in items:
if not isinstance(item, dict):
raise ValueError('黑名单选择无效,请刷新后重试')
account, conversation = item.get('account'), item.get('conversation')
if not isinstance(account, str) or not account.strip() or not isinstance(conversation, str) or not conversation.strip():
raise ValueError('黑名单选择无效,请刷新后重试')
pairs.add((account.strip(), conversation.strip()))
path = _path(root)
if not path.exists():
return 0
with closing(sqlite3.connect(path, timeout=5)) as db, db:
before = db.total_changes
db.executemany('DELETE FROM blocked WHERE account=? AND conversation=?', sorted(pairs))
return db.total_changes - before
def blocked_reason(account, conversation, *, root=None):
try:
return BLOCKED_REASON if (str(account or ''), str(conversation or '')) in entries(root) else ''
except (OSError, sqlite3.Error):
return '黑名单暂不可读取,已暂停系统发送,请重试'
def state_reason(state):
state = state if isinstance(state, dict) else {}
event = state.get('database_event') or {}
return blocked_reason(state.get('account') or event.get('account'),
state.get('conv_id') or event.get('conv_id'))