Files
dsh 0824e0ef83 v1.2.0: 事件流对账、增量 update、ZIM 发布与表情渲染
从东方年代记吧一次性备份脚本整理成的贴吧存档工具:crawl/update/verify/as-of/restore/rebuild/images/build-zim,SQLite 事件流 + 回收站 + 中文全文索引 ZIM。
2026-11-18 11:41:25 +08:00

68 lines
2.6 KiB
Python

# -*- coding: utf-8 -*-
"""restore:把回收站里的东西捞回来(手动操作,也会记事件)。
支持三种粒度:
* ``--tid``:整帖恢复(先发 thread_restored,再把该帖剩下单独删的楼层逐个恢复)
* ``--pid``:单层恢复
* ``--cid``:单条楼中楼恢复
恢复也走事件流(``post_restored`` / ``comment_restored`` / ``thread_restored``),
所以 as-of 之后再看,历史是连贯的。
"""
from __future__ import annotations
import sqlite3
from . import db, events
from .config import Config
def restore(cfg: Config, tid: int | None = None, pid: int | None = None,
cid: int | None = None) -> dict:
conn = db.connect(cfg)
db.init_db(conn)
db.ensure_compat(conn)
batch = events.start_batch(conn, "restore")
log = events.EventLog(conn, cfg, batch, "restore")
stats = {"threads": 0, "posts": 0, "comments": 0}
def emit(kind, **kw):
ev = log.emit(kind, source="manual", **kw)
events.apply_event(conn, ev)
try:
if tid:
row = conn.execute("SELECT deleted_at FROM thread WHERE tid=?", (tid,)).fetchone()
if row is None:
raise SystemExit(f"没有这个主题:tid={tid}")
# 先记下来:thread_restored 会把跟着整帖进回收站的楼一次性翻回去
rows = conn.execute(
"SELECT pid, recycle_reason FROM post WHERE tid=? AND status='recycled'", (tid,)
).fetchall()
if row[0]:
emit("thread_restored", tid=tid, evidence="manual restore")
stats["threads"] += 1
stats["posts"] += sum(1 for _pid, reason in rows if reason == "thread_deleted")
for pid_row, reason in rows:
if reason == "thread_deleted":
continue
emit("post_restored", tid=tid, pid=int(pid_row), evidence="manual restore")
stats["posts"] += 1
for (cid_row,) in conn.execute(
"SELECT cid FROM comment WHERE tid=? AND status='recycled'", (tid,)
).fetchall():
emit("comment_restored", tid=tid, cid=int(cid_row), evidence="manual restore")
stats["comments"] += 1
if pid:
emit("post_restored", pid=pid, evidence="manual restore")
stats["posts"] += 1
if cid:
emit("comment_restored", cid=cid, evidence="manual restore")
stats["comments"] += 1
conn.commit()
finally:
log.close()
events.finish_batch(conn, batch)
conn.commit()
return stats