# -*- coding: utf-8 -*- """Write WeChat-safe digital-nomad audit booklet into prod DB.""" from __future__ import annotations import json import re import time from pathlib import Path import paramiko HERE = Path(__file__).resolve().parent MD = (HERE / "audit_book_seed.md").read_text(encoding="utf-8") HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805" def split_markdown_chapters(md: str) -> list[dict]: text = (md or "").replace("\r\n", "\n").replace("\r", "\n").strip() if not text: return [] parts = re.split(r"(?m)^(#{1} .+)$", text) chapters: list[dict] = [] preamble = (parts[0] or "").strip() order = 1 if preamble and len(parts) == 1: return [{"id": "c1", "title": "正文", "order": 1, "content": preamble + "\n"}] if preamble: chapters.append({"id": "c0", "title": "前言", "order": order, "content": preamble + "\n"}) order += 1 i = 1 while i < len(parts): heading = parts[i].strip() body = parts[i + 1] if i + 1 < len(parts) else "" title = re.sub(r"^#\s+", "", heading).strip() or f"第{order}章" content = f"{heading}\n{body}".strip() + "\n" chapters.append({"id": f"c{order}", "title": title, "order": order, "content": content}) order += 1 i += 2 return chapters def main() -> int: chapters = split_markdown_chapters(MD) assert chapters, "no chapters" payload = { "title": "数字游民入门指南", "subtitle": "远程办公 · 自律生活 · 稳健成长", "description": "面向普通人的数字游民与远程办公入门读本:时间管理、协作沟通、健康作息与职业成长。", "chapters": chapters, } raw = json.dumps(payload, ensure_ascii=False).encode("utf-8") c = paramiko.SSHClient() c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) c.connect(HOST, username=USER, password=PASS, timeout=60, allow_agent=False, look_for_keys=False) sftp = c.open_sftp() with sftp.file("/tmp/audit_book_seed.json", "wb") as rf: rf.write(raw) sftp.close() cmd = r""" set -e python3 <<'PY' import json, sqlite3, time data=json.load(open('/tmp/audit_book_seed.json',encoding='utf-8')) chapters=data['chapters'] con=sqlite3.connect('/opt/nomadmini/data/nomadmini.db') now=time.time() row=con.execute("select id from books where id='audit'").fetchone() meta=( data['title'], data['subtitle'], '', '📗', data['description'], json.dumps(['数字游民','远程办公','生活方式'], ensure_ascii=False), 0, '', 100, 5.0, json.dumps(chapters, ensure_ascii=False), now, ) if row: con.execute( 'UPDATE books SET title=?, subtitle=?, author=?, cover_emoji=?, description=?, tags=?,' ' price_fen=?, product_id=?, unlock_percent=?, rating=?, chapters_json=?, updated_at=? WHERE id=?', meta + ('audit',), ) else: con.execute( 'INSERT INTO books(id,title,subtitle,author,cover_emoji,description,tags,' 'price_fen,product_id,unlock_percent,rating,chapters_json,updated_at) ' "VALUES ('audit',?,?,?,?,?,?,?,?,?,?,?,?)", meta, ) con.commit() print('chapters', len(chapters)) print('titles', [c['title'] for c in chapters]) print('words', sum(len(c.get('content') or '') for c in chapters)) PY curl -sk -o /tmp/audit_check.json -w "audit %{http_code}\n" https://api.nomadro.cn/api/ebook/books/audit python3 <<'PY' import json d=json.load(open('/tmp/audit_check.json',encoding='utf-8')) print('api', d.get('title'), d.get('chapter_count'), d.get('is_free')) print('toc', [c.get('title') for c in (d.get('chapters') or [])]) PY rm -f /tmp/audit_book_seed.json /tmp/audit_check.json """ _, stdout, _ = c.exec_command(cmd, timeout=90, get_pty=True) while not stdout.channel.exit_status_ready(): if stdout.channel.recv_ready(): print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True) time.sleep(0.05) while stdout.channel.recv_ready(): print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True) code = stdout.channel.recv_exit_status() print(f"[exit {code}]", flush=True) c.close() return code if __name__ == "__main__": raise SystemExit(main())