Files
Lark-Snooper/snooper_web.py

535 lines
20 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""Local-only web UI for searching chats and maintaining chats.exclude."""
from __future__ import annotations
import hmac
import ipaddress
import json
import os
import re
import secrets
import stat
import tempfile
import threading
import webbrowser
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from typing import Any
from urllib.parse import parse_qs, urlsplit
import yaml
from snooper_summary import SummaryError, load_config, resolve_chat_rules
class WebError(RuntimeError):
"""Web configuration failed without exposing message contents."""
def _line_indent(line: str) -> int:
return len(line) - len(line.lstrip(" "))
def _is_ignored_yaml_line(line: str) -> bool:
stripped = line.strip()
return not stripped or stripped.startswith("#")
def _inline_comment(line: str) -> str:
"""Return a YAML inline comment, ignoring # characters inside quotes."""
single = double = escaped = False
for index, char in enumerate(line):
if escaped:
escaped = False
continue
if char == "\\" and double:
escaped = True
continue
if char == "'" and not double:
single = not single
elif char == '"' and not single:
double = not double
elif (
char == "#"
and not single
and not double
and (index == 0 or line[index - 1].isspace())
):
return line[index:].rstrip("\r\n")
return ""
def _block_end(lines: list[str], start: int, indent: int) -> int:
for index in range(start + 1, len(lines)):
line = lines[index]
if not _is_ignored_yaml_line(line) and _line_indent(line) <= indent:
return index
return len(lines)
def _replace_end(lines: list[str], start: int, end: int, indent: int) -> int:
"""Keep blank lines and outdented comments after a YAML block in place."""
replace_end = end
while replace_end > start + 1:
line = lines[replace_end - 1]
if not _is_ignored_yaml_line(line):
break
if line.strip() and _line_indent(line) > indent:
break
replace_end -= 1
return replace_end
def _new_item(chat_id: str, indent: int) -> str:
return f"{' ' * indent}- {json.dumps(chat_id, ensure_ascii=False)}\n"
def _render_exclude(lines: list[str], index: int, indent: int, chat_ids: list[str]) -> list[str]:
end = _block_end(lines, index, indent)
replace_end = _replace_end(lines, index, end, indent)
key_comment = _inline_comment(lines[index])
comment_suffix = f" {key_comment}" if key_comment else ""
old_items: dict[str, str] = {}
preserved: list[str] = []
item_pattern = re.compile(r"^\s+-\s*(.*?)\s*(?:\r?\n)?$")
for line in lines[index + 1 : replace_end]:
match = item_pattern.match(line)
if not match:
preserved.append(line)
continue
try:
value = yaml.safe_load(match.group(1))
except yaml.YAMLError:
continue
if isinstance(value, bool) or not isinstance(value, (str, int)):
continue
chat_id = str(value).strip()
if chat_id and chat_id not in old_items:
old_items[chat_id] = line
if not chat_ids:
replacement = [f"{' ' * indent}exclude: []{comment_suffix}\n"]
else:
replacement = [f"{' ' * indent}exclude:{comment_suffix}\n"]
replacement.extend(preserved)
replacement.extend(
old_items.get(chat_id) or _new_item(chat_id, indent + 2)
for chat_id in chat_ids
)
return lines[:index] + replacement + lines[replace_end:]
def update_yaml_excludes(text: str, chat_ids: list[str]) -> str:
"""Update only chats.exclude, retaining unrelated YAML and item comments."""
lines = text.splitlines(keepends=True)
if lines and not lines[-1].endswith(("\n", "\r")):
lines[-1] += "\n"
chats_pattern = re.compile(r"^chats:\s*(?:\{\s*\})?\s*(?:#.*)?(?:\r?\n)?$")
chats_index = next(
(index for index, line in enumerate(lines) if chats_pattern.match(line)),
None,
)
if chats_index is None and any(
re.match(r"^chats\s*:", line) for line in lines
):
raise WebError("请将 chats 改为多行 YAML 对象后再使用 Web 管理;原配置未修改。")
if chats_index is None:
if lines and lines[-1].strip():
lines.append("\n")
lines.append("chats:\n")
lines.extend(_new_item(chat_id, 4) for chat_id in chat_ids)
if chat_ids:
lines.insert(-len(chat_ids), " exclude:\n")
else:
lines.append(" exclude: []\n")
return "".join(lines)
chats_comment = _inline_comment(lines[chats_index])
if "{" in lines[chats_index]:
replacement = ["chats:" + (f" {chats_comment}" if chats_comment else "") + "\n"]
if chat_ids:
replacement.append(" exclude:\n")
replacement.extend(_new_item(chat_id, 4) for chat_id in chat_ids)
else:
replacement.append(" exclude: []\n")
return "".join(lines[:chats_index] + replacement + lines[chats_index + 1 :])
chats_end = _block_end(lines, chats_index, 0)
key_pattern = re.compile(r"^(\s+)[A-Za-z_][\w-]*\s*:")
child_indents = [
len(match.group(1))
for line in lines[chats_index + 1 : chats_end]
if not _is_ignored_yaml_line(line)
if (match := key_pattern.match(line))
]
child_indent = min(child_indents, default=2)
exclude_pattern = re.compile(rf"^ {{{child_indent}}}exclude\s*:")
exclude_index = next(
(
index
for index in range(chats_index + 1, chats_end)
if exclude_pattern.match(lines[index])
),
None,
)
if exclude_index is not None:
return "".join(_render_exclude(lines, exclude_index, child_indent, chat_ids))
insertion = [f"{' ' * child_indent}exclude:" + (" []\n" if not chat_ids else "\n")]
insertion.extend(_new_item(chat_id, child_indent + 2) for chat_id in chat_ids)
return "".join(lines[: chats_index + 1] + insertion + lines[chats_index + 1 :])
class ChatConfig:
"""Thread-safe, atomic updates to the existing YAML configuration."""
def __init__(self, path: Path | str = "config.yaml"):
self.path = Path(path).expanduser()
self._lock = threading.Lock()
def excluded(self) -> list[str]:
if not self.path.exists():
return []
config = load_config(self.path)
excluded, _ = resolve_chat_rules(config)
return excluded
def set_ignored(self, chat_id: Any, ignored: Any) -> list[str]:
if isinstance(chat_id, bool) or not isinstance(chat_id, (str, int)):
raise WebError("chat_id 必须是字符串或整数。")
chat_id = str(chat_id).strip()
if not chat_id:
raise WebError("chat_id 不能为空。")
if type(ignored) is not bool:
raise WebError("ignored 必须是布尔值。")
with self._lock:
excluded = self.excluded()
if ignored and chat_id not in excluded:
excluded.append(chat_id)
elif not ignored:
excluded = [item for item in excluded if item != chat_id]
text = self.path.read_text(encoding="utf-8") if self.path.exists() else ""
rendered = update_yaml_excludes(text, excluded)
# Validate the complete rendered file before replacing the original.
config = yaml.safe_load(rendered) or {}
resolve_chat_rules(config)
self._atomic_write(rendered)
return excluded
def _atomic_write(self, text: str) -> None:
self.path.parent.mkdir(parents=True, exist_ok=True)
mode = (
stat.S_IMODE(self.path.stat().st_mode)
if self.path.exists()
else 0o600
)
descriptor, temporary = tempfile.mkstemp(
prefix=f".{self.path.name}.", dir=self.path.parent
)
try:
with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
handle.write(text)
handle.flush()
os.fsync(handle.fileno())
os.chmod(temporary, mode)
os.replace(temporary, self.path)
finally:
try:
os.unlink(temporary)
except FileNotFoundError:
pass
def _chat_type(value: Any) -> int:
if isinstance(value, int):
return value
return {"PRIVATE": 1, "GROUP": 2, "TOPIC_GROUP": 3}.get(str(value), 0)
def _record(chat: Any, source: str) -> dict[str, Any]:
if isinstance(chat, dict):
chat_id = str(chat.get("id") or chat.get("chat_id") or "")
name = chat.get("name") or ""
chat_type = _chat_type(chat.get("type", chat.get("chat_type", 0)))
else:
chat_id = str(chat.chat_id)
name = chat.name or ""
chat_type = _chat_type(chat.chat_type)
return {
"chat_id": chat_id,
"name": str(name).strip(),
"chat_type": chat_type,
"ignored": False,
"sources": [source],
}
def _private_peer_id(chat: dict[str, Any], own_id: str) -> str:
"""Find the other participant without another request for ordinary P2P chats."""
if _chat_type(chat.get("type", chat.get("chat_type", 0))) != 1:
return ""
key_parts = str(chat.get("key") or "").split(":")
if len(key_parts) == 2:
if key_parts[0] == own_id and key_parts[1] != own_id:
return key_parts[1]
if key_parts[1] == own_id and key_parts[0] != own_id:
return key_parts[0]
owner_id = str(chat.get("ownerId") or "")
return owner_id if owner_id and owner_id != own_id else ""
def fill_member_names(client: Any, chats: list[dict[str, Any]]) -> tuple[list[dict[str, Any]], list[str]]:
"""Fill only missing names: batch P2P peers, then read unnamed group members."""
from snooper_contacts import _chat_member_names, _sender_names
resolved = [dict(chat) for chat in chats]
own_id = str(getattr(client.auth, "user_id", "") or "")
private_peers = {
index: peer_id
for index, chat in enumerate(resolved)
if not str(chat.get("name") or "").strip()
if (peer_id := _private_peer_id(chat, own_id))
}
warnings: list[str] = []
peer_names: dict[str, str] = {}
private_lookup_failed = False
if private_peers:
try:
peer_names = _sender_names(client, private_peers.values())
except Exception as error: # noqa: BLE001 - names are an optional display fallback
private_lookup_failed = True
warnings.append(f"私聊成员姓名批量补全失败({type(error).__name__})。")
for index, peer_id in private_peers.items():
if peer_id in peer_names:
resolved[index]["name"] = peer_names[peer_id]
member_failures = 0
for chat in resolved:
if str(chat.get("name") or "").strip():
continue
chat_type = _chat_type(chat.get("type", chat.get("chat_type", 0)))
if chat_type not in (1, 2, 3) or (chat_type == 1 and private_lookup_failed):
continue
try:
members = _chat_member_names(client, str(chat.get("id") or ""))
other_names = [
name for user_id, name in members.items() if str(user_id) != own_id
]
if not other_names:
other_names = list(members.values())
if other_names:
chat["name"] = "、".join(other_names)
except Exception: # noqa: BLE001 - one unnamed chat must not fail the full list
member_failures += 1
if member_failures:
warnings.append(f"有 {member_failures} 个无名会话的成员姓名补全失败。")
return resolved, warnings
def chat_snapshot(config: ChatConfig, refresh: bool = False) -> dict[str, Any]:
"""Merge visible Feishu chats, local names and stale excluded IDs."""
from snooper_storage import SnifferStorage as Storage
warnings: list[str] = []
refresh_succeeded = False
records: dict[str, dict[str, Any]] = {}
order: list[str] = []
def merge(chat: Any, source: str) -> None:
record = _record(chat, source)
chat_id = record["chat_id"]
if not chat_id:
return
if chat_id not in records:
records[chat_id] = record
order.append(chat_id)
return
current = records[chat_id]
if record["name"] and (not current["name"] or source == "feishu"):
current["name"] = record["name"]
if record["chat_type"] and (not current["chat_type"] or source == "feishu"):
current["chat_type"] = record["chat_type"]
if source not in current["sources"]:
current["sources"].append(source)
if refresh:
try:
from larkx.auth import LarkAuth
from snooper_client import SnifferLarkClient as LarkClient
from snooper_history import _feed_chats
client = LarkClient(LarkAuth())
remote_chats, name_warnings = fill_member_names(
client, list(_feed_chats(client))
)
warnings.extend(name_warnings)
for chat in remote_chats:
merge(chat, "feishu")
refresh_succeeded = True
except Exception as error: # noqa: BLE001 - keep local management available offline
warnings.append(
f"飞书会话刷新失败({type(error).__name__}),当前显示本地与配置中的会话。"
)
try:
for chat in Storage().list_chats(limit=100000):
merge(chat, "local")
except Exception as error: # noqa: BLE001 - remote/config data can still be useful
warnings.append(f"本地会话读取失败({type(error).__name__})。")
excluded = config.excluded()
for chat_id in excluded:
if chat_id not in records:
records[chat_id] = {
"chat_id": chat_id,
"name": "",
"chat_type": 0,
"ignored": True,
"sources": ["config"],
}
order.append(chat_id)
records[chat_id]["ignored"] = True
chats = [records[chat_id] for chat_id in order]
return {
"chats": chats,
"excluded": excluded,
"refreshed": refresh and refresh_succeeded,
"warnings": warnings,
}
def _is_loopback(host: str) -> bool:
if host.lower() == "localhost":
return True
try:
return ipaddress.ip_address(host).is_loopback
except ValueError:
return False
class SnooperWebServer(ThreadingHTTPServer):
daemon_threads = True
def __init__(self, address: tuple[str, int], config: ChatConfig):
super().__init__(address, SnooperWebHandler)
self.config = config
self.csrf_token = secrets.token_urlsafe(32)
class SnooperWebHandler(BaseHTTPRequestHandler):
server: SnooperWebServer
def _send(self, status: int, content: bytes, content_type: str) -> None:
self.send_response(status)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(content)))
self.send_header("Cache-Control", "no-store")
self.send_header("X-Content-Type-Options", "nosniff")
self.send_header("Referrer-Policy", "no-referrer")
self.send_header("Content-Security-Policy", "frame-ancestors 'none'; base-uri 'none'")
self.end_headers()
self.wfile.write(content)
def _json(self, status: int, value: Any) -> None:
content = json.dumps(value, ensure_ascii=False).encode("utf-8")
self._send(status, content, "application/json; charset=utf-8")
def _valid_host(self) -> bool:
try:
host = urlsplit(f"//{self.headers.get('Host', '')}").hostname
except ValueError:
return False
return bool(host and _is_loopback(host))
def _authorized_write(self) -> bool:
origin = self.headers.get("Origin")
expected_origin = f"http://{self.headers.get('Host', '')}"
token = self.headers.get("X-CSRF-Token", "")
return (
self.headers.get_content_type() == "application/json"
and (not origin or origin == expected_origin)
and hmac.compare_digest(token, self.server.csrf_token)
)
def do_GET(self) -> None:
if not self._valid_host():
self._json(403, {"error": "仅允许通过本机地址访问。"})
return
route = urlsplit(self.path)
if route.path == "/":
template = Path(__file__).with_name("snooper_web.html").read_text(encoding="utf-8")
content = template.replace("__CSRF_TOKEN__", self.server.csrf_token).encode("utf-8")
self._send(200, content, "text/html; charset=utf-8")
return
if route.path == "/api/chats":
refresh = parse_qs(route.query).get("refresh", [""])[-1] == "1"
try:
self._json(200, chat_snapshot(self.server.config, refresh=refresh))
except (OSError, SummaryError, WebError, yaml.YAMLError) as error:
self._json(400, {"error": str(error)})
return
self._json(404, {"error": "页面不存在。"})
def do_POST(self) -> None:
if not self._valid_host():
self._json(403, {"error": "仅允许通过本机地址访问。"})
return
if urlsplit(self.path).path != "/api/ignore":
self._json(404, {"error": "页面不存在。"})
return
if not self._authorized_write():
self._json(403, {"error": "写入校验失败,请刷新页面后重试。"})
return
try:
length = int(self.headers.get("Content-Length", "0"))
if not 0 < length <= 16384:
raise WebError("请求大小不正确。")
payload = json.loads(self.rfile.read(length).decode("utf-8"))
if not isinstance(payload, dict):
raise WebError("请求必须是 JSON 对象。")
excluded = self.server.config.set_ignored(
payload.get("chat_id"), payload.get("ignored")
)
self._json(
200,
{
"chat_id": str(payload.get("chat_id")).strip(),
"ignored": payload.get("ignored"),
"excluded": excluded,
},
)
except (WebError, SummaryError, OSError, ValueError, yaml.YAMLError) as error:
self._json(400, {"error": str(error)})
except Exception: # noqa: BLE001 - do not leak internals through the local API
self._json(500, {"error": "配置写入失败,请检查文件权限后重试。"})
def run_web(
host: str = "127.0.0.1",
port: int = 8765,
config_path: Path | str = "config.yaml",
open_browser: bool = True,
) -> None:
if not _is_loopback(host):
raise WebError("Web 管理页仅允许监听本机回环地址。")
if not 0 <= port <= 65535:
raise WebError("端口必须在 0 到 65535 之间。")
server = SnooperWebServer((host, port), ChatConfig(config_path))
actual_port = server.server_address[1]
url = f"http://{host}:{actual_port}"
print(f"会话过滤管理: {url}(配置: {ChatConfig(config_path).path})")
print("仅监听本机;按 Ctrl+C 停止。")
if open_browser:
threading.Timer(0.2, webbrowser.open, args=(url,)).start()
try:
server.serve_forever()
except KeyboardInterrupt:
print("\n已停止 Web 管理页。")
finally:
server.server_close()