From 1de7078f9d6903fae94928da27838ae6dc145b2a Mon Sep 17 00:00:00 2001 From: areyoubugcoder <241083775+areyoubugcoder@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:07:04 +0800 Subject: [PATCH 01/10] Add per-article interaction count collection --- SECURITY.md | 2 +- crates/core/src/model.rs | 1 + crates/core/src/store.rs | 35 +- crates/core/src/workbench/interactions.rs | 493 ++++++++++++++++++++++ crates/core/src/workbench/mod.rs | 1 + frontend/src/lib/tauri.ts | 8 + frontend/src/lib/workbench.ts | 6 + frontend/src/views/Workbench.tsx | 62 ++- src-tauri/src/lib.rs | 3 + src-tauri/src/workbench.rs | 82 ++++ 10 files changed, 685 insertions(+), 8 deletions(-) create mode 100644 crates/core/src/workbench/interactions.rs diff --git a/SECURITY.md b/SECURITY.md index f60fe95..61a5f8c 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -1,6 +1,6 @@ # 安全政策 -MPider 当前工作台在本机通过 Frida 观察已登录微信并保存会话材料。它不需要安装根证书或修改系统代理;历史代理/getmsg 实现仍保留在源码中,调用旧入口时另有证书与系统代理风险。 +MPider 的原生列表采集在本机通过 Frida 观察已登录微信并保存会话材料,无需根证书或系统代理。文章库的单篇互动补采是独立操作,需要受信任的 MPider 证书,并在用户打开文章时短暂启用本地代理。仅为所选文章保存服务端返回的互动计数。 ## 报告漏洞 diff --git a/crates/core/src/model.rs b/crates/core/src/model.rs index 0595968..ca64474 100644 --- a/crates/core/src/model.rs +++ b/crates/core/src/model.rs @@ -396,6 +396,7 @@ pub struct ArticleFields { /// 文章列表行(`list_articles` 返回的精简投影,对齐 Python 的列裁剪)。 #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] pub struct ArticleRow { + pub interactions: crate::workbench::interactions::ArticleInteractions, /// 本地存在非空 Markdown 正文,独立于旧详情状态。 #[serde(default)] pub has_body: bool, diff --git a/crates/core/src/store.rs b/crates/core/src/store.rs index 02e971c..7f8d01a 100644 --- a/crates/core/src/store.rs +++ b/crates/core/src/store.rs @@ -2107,7 +2107,7 @@ impl Store { ) -> Result> { let mut sql = String::from( "SELECT id, biz, mid, idx, title, author, digest, content_url, \ - published_at, detail_done, is_deleted, detail_error, length(trim(COALESCE(content_md,''),char(9)||char(10)||char(13)||char(32)))>0 FROM articles WHERE is_deleted=0", + published_at, detail_done, is_deleted, detail_error, length(trim(COALESCE(content_md,''),char(9)||char(10)||char(13)||char(32)))>0, read_num, old_like_num, like_num, comment_count FROM articles WHERE is_deleted=0", ); let (filter, mut args) = Self::article_filter(biz, title, downloaded); sql.push_str(&filter); @@ -2137,6 +2137,7 @@ impl Store { is_deleted: r.get(10)?, detail_error: r.get(11)?, has_body: r.get(12)?, + interactions: Self::read_article_interactions(r)?, }) })?; Ok(rows.collect::>>()?) @@ -2152,7 +2153,7 @@ impl Store { ) -> Result> { let mut sql = String::from( "SELECT id, biz, mid, idx, title, author, digest, content_url, \ - published_at, detail_done, is_deleted, detail_error, length(trim(COALESCE(content_md,''),char(9)||char(10)||char(13)||char(32)))>0 FROM articles \ + published_at, detail_done, is_deleted, detail_error, length(trim(COALESCE(content_md,''),char(9)||char(10)||char(13)||char(32)))>0, read_num, old_like_num, like_num, comment_count FROM articles \ WHERE is_deleted=0 AND detail_done=0 AND content_url IS NOT NULL AND content_url != ''", ); let mut args: Vec = Vec::new(); @@ -2192,6 +2193,7 @@ impl Store { is_deleted: r.get(10)?, detail_error: r.get(11)?, has_body: r.get(12)?, + interactions: Self::read_article_interactions(r)?, }) })?; Ok(rows.collect::>>()?) @@ -2274,7 +2276,7 @@ impl Store { let row = conn .query_row( "SELECT id, biz, mid, idx, title, author, digest, content_url, \ - published_at, detail_done, is_deleted, detail_error, content_md FROM articles WHERE id=?", + published_at, detail_done, is_deleted, detail_error, content_md, read_num, old_like_num, like_num, comment_count FROM articles WHERE id=?", params![id], |r| { Ok(( @@ -2291,6 +2293,7 @@ impl Store { detail_done: r.get(9)?, is_deleted: r.get(10)?, detail_error: r.get(11)?, + interactions: Self::read_article_interactions(r)?, has_body: r.get::<_, Option>(12)?.is_some_and(|md| !md.trim().is_empty()), }, r.get::<_, Option>(12)?, @@ -2301,6 +2304,32 @@ impl Store { Ok(row) } + fn read_article_interactions( + row: &rusqlite::Row<'_>, + ) -> rusqlite::Result { + Ok(crate::workbench::interactions::ArticleInteractions { + read_count: row.get(13)?, + like_count: row.get(14)?, + watching_count: row.get(15)?, + comment_count: row.get(16)?, + }) + } + + pub fn save_article_interactions( + &self, + id: i64, + metrics: &crate::workbench::interactions::ArticleInteractions, + ) -> Result<()> { + let updated = self.conn().execute( + "UPDATE articles SET read_num=COALESCE(?1,read_num), old_like_num=COALESCE(?2,old_like_num), + like_num=COALESCE(?3,like_num), comment_count=COALESCE(?4,comment_count) + WHERE id=?5 AND is_deleted=0", + params![metrics.read_count, metrics.like_count, metrics.watching_count, metrics.comment_count, id], + )?; + anyhow::ensure!(updated == 1, "文章已删除"); + Ok(()) + } + /// 文章计数(控制面板状态卡用):(总数, 已采详情数, 待补数),均不含已删除。 /// 待补 = 未采且还会被自动批量处理的(排除不可用 detail_done=-1、失败满 3 次、无链接)。 pub fn article_counts(&self) -> Result<(i64, i64, i64)> { diff --git a/crates/core/src/workbench/interactions.rs b/crates/core/src/workbench/interactions.rs new file mode 100644 index 0000000..7d6c8cf --- /dev/null +++ b/crates/core/src/workbench/interactions.rs @@ -0,0 +1,493 @@ +//! Save metrics returned while the user opens a selected article in WeChat. +use serde::{Deserialize, Serialize}; +#[cfg(any(windows, test))] +use serde_json::Value; + +#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)] +pub struct ArticleInteractions { + pub read_count: Option, + pub like_count: Option, + pub watching_count: Option, + pub comment_count: Option, +} + +#[cfg(any(windows, test))] +impl ArticleInteractions { + fn parse(payload: &Value) -> Option { + let obj = payload.as_object()?; + for ret in [obj.get("ret"), payload.pointer("/base_resp/ret")] + .into_iter() + .flatten() + { + if count(Some(ret)) != Some(0) { + return None; + } + } + let stats = payload.get("appmsgstat").unwrap_or(&Value::Null); + let metrics = Self { + read_count: count(stats.get("read_num")), + like_count: count(stats.get("old_like_num")), + watching_count: count(stats.get("like_num")), + comment_count: count(payload.get("comment_count")) + .or_else(|| count(stats.get("comment_count"))), + }; + (metrics != Self::default()).then_some(metrics) + } + + fn parse_html(html: &str) -> Option { + use std::sync::LazyLock; + + static ARTICLE_CONTENT: LazyLock = LazyLock::new(|| { + regex::Regex::new(r#"(?i)<[a-z][a-z0-9]*[^>]*\sid\s*=\s*["']js_content["']"#).unwrap() + }); + static SCRIPTS: LazyLock = + LazyLock::new(|| regex::Regex::new(r"(?is)]*>(.*?)").unwrap()); + static COUNTS: LazyLock = LazyLock::new(|| { + regex::Regex::new( + r#"\b(read_num|old_like_num|like_num|comment_count)\b\\?["']?\s*[:=]\s*\\?["']?([0-9]+)\b"#, + ) + .unwrap() + }); + if !ARTICLE_CONTENT.is_match(html) { + return None; + } + + let mut values = [None; 4]; + let mut ambiguous = [false; 4]; + for script in SCRIPTS.captures_iter(html) { + let source = script.get(1)?.as_str(); + for entry in COUNTS.captures_iter(source) { + let index = match &entry[1] { + "read_num" => 0, + "old_like_num" => 1, + "like_num" => 2, + "comment_count" => 3, + _ => continue, + }; + if let Ok(value) = entry[2].parse::() { + ambiguous[index] |= values[index].is_some_and(|prior| prior != value); + values[index] = Some(value); + } + } + } + for (value, is_ambiguous) in values.iter_mut().zip(ambiguous) { + if is_ambiguous { + *value = None; + } + } + let [read_count, like_count, watching_count, comment_count] = values; + let metrics = Self { + read_count, + like_count, + watching_count, + comment_count, + }; + (metrics != Self::default()).then_some(metrics) + } +} + +#[cfg(any(windows, test))] +fn count(value: Option<&Value>) -> Option { + let value = value?; + value + .as_i64() + .or_else(|| value.as_str()?.parse().ok()) + .filter(|number| *number >= 0) +} + +#[cfg(any(windows, test))] +mod capture { + use std::sync::{Arc, Mutex}; + + use anyhow::{Context, Result}; + use http_body_util::BodyExt; + use hudsucker::hyper::{header, Method, Request, Response}; + use hudsucker::rustls::server::ClientHello; + use hudsucker::{decode_response, Body, HttpContext, HttpHandler, RequestOrResponse}; + use tokio::sync::oneshot; + + use super::ArticleInteractions; + + const HOST: &str = "mp.weixin.qq.com"; + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + enum ArticleResponse { + Page, + Stats, + } + + impl ArticleResponse { + fn max_bytes(self) -> usize { + match self { + Self::Page => 6 * 1024 * 1024, + Self::Stats => 1024 * 1024, + } + } + + fn parse(self, body: &[u8]) -> Option { + match self { + Self::Page => ArticleInteractions::parse_html(std::str::from_utf8(body).ok()?), + Self::Stats => serde_json::from_slice(body) + .ok() + .as_ref() + .and_then(ArticleInteractions::parse), + } + } + } + + #[derive(Clone)] + pub(super) struct ArticleIdentity { + pub biz: String, + pub mid: String, + pub idx: i64, + } + + impl ArticleIdentity { + fn response_kind(&self, req: &Request) -> Option { + let kind = match (req.method(), req.uri().path()) { + (&Method::GET, "/s") => ArticleResponse::Page, + (&Method::POST, "/mp/getappmsgext") => ArticleResponse::Stats, + _ => return None, + }; + if req + .uri() + .host() + .or_else(|| req.headers().get(header::HOST)?.to_str().ok()) + != Some(HOST) + || !req + .headers() + .get(header::USER_AGENT) + .and_then(|value| value.to_str().ok()) + .is_some_and(|ua| ua.contains("MicroMessenger")) + { + return None; + } + let mut biz = false; + let mut mid = false; + let mut idx = false; + for (key, value) in + url::form_urlencoded::parse(req.uri().query().unwrap_or("").as_bytes()) + { + match key.as_ref() { + "__biz" if !biz && value == self.biz => biz = true, + "mid" if !mid && value == self.mid => mid = true, + "idx" if !idx && value.parse::() == Ok(self.idx) => idx = true, + "__biz" | "mid" | "idx" => return None, + _ => {} + } + } + (biz && mid && idx).then_some(kind) + } + } + + type Sender = oneshot::Sender; + + #[derive(Clone)] + pub(super) struct Handler { + target: Arc, + sender: Arc>>, + response_kind: Option, + } + + impl Handler { + pub fn new(target: ArticleIdentity, sender: Sender) -> Self { + Self { + target: Arc::new(target), + sender: Arc::new(Mutex::new(Some(sender))), + response_kind: None, + } + } + + async fn observe(&self, response: Response, kind: ArticleResponse) -> Response { + use hudsucker::hyper::body::Body as _; + let limit = kind.max_bytes(); + if !response.status().is_success() || response.body().size_hint().lower() > limit as u64 + { + return response; + } + + let (parts, body) = response.into_parts(); + let Ok(body) = body.collect().await else { + return Response::from_parts(parts, Body::empty()); + }; + let bytes = body.to_bytes(); + if bytes.len() <= limit { + let mut copy = Response::new(Body::from(bytes.clone())); + *copy.headers_mut() = parts.headers.clone(); + if let Ok(decoded) = decode_response(copy) { + if let Ok(body) = http_body_util::Limited::new(decoded.into_body(), limit) + .collect() + .await + { + if let Some(metrics) = kind.parse(&body.to_bytes()) { + if let Some(sender) = self.sender.lock().unwrap().take() { + let _ = sender.send(metrics); + } + } + } + } + } + Response::from_parts(parts, Body::from(bytes)) + } + } + + impl HttpHandler for Handler { + async fn should_intercept_connect(&mut self, _: &HttpContext, req: &Request) -> bool { + req.uri().host() == Some(HOST) + } + + async fn should_intercept_tls(&mut self, _: &HttpContext, hello: ClientHello<'_>) -> bool { + hello.server_name() == Some(HOST) + } + + async fn handle_request( + &mut self, + _: &HttpContext, + request: Request, + ) -> RequestOrResponse { + let waiting = self + .sender + .lock() + .unwrap() + .as_ref() + .is_some_and(|sender| !sender.is_closed()); + self.response_kind = if waiting { + self.target.response_kind(&request) + } else { + None + }; + request.into() + } + + async fn handle_response( + &mut self, + _: &HttpContext, + response: Response, + ) -> Response { + if let Some(kind) = self.response_kind { + return self.observe(response, kind).await; + } + response + } + } + + pub(super) async fn run( + ca: crate::ca::CaMaterial, + target: ArticleIdentity, + install_proxy: impl FnOnce(u16) -> std::result::Result, + ready: impl FnOnce(), + ) -> Result { + use hudsucker::rustls::crypto::aws_lc_rs; + use hudsucker::Proxy; + use std::time::Duration; + + let _guard = crate::runstate::try_acquire_run().context("已有代理采集任务在运行")?; + crate::capture::install_default_crypto(); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?; + let port = listener.local_addr()?.port(); + let (sender, result) = oneshot::channel(); + let (shutdown_tx, shutdown_rx) = oneshot::channel(); + let proxy = Proxy::builder() + .with_listener(listener) + .with_ca(ca.authority()?) + .with_rustls_connector(aws_lc_rs::default_provider()) + .with_http_handler(Handler::new(target, sender)) + .with_graceful_shutdown(async move { + let _ = shutdown_rx.await; + }) + .build()?; + let mut proxy = tokio::spawn(proxy.start()); + let proxy_guard = match install_proxy(port) { + Ok(guard) => guard, + Err(error) => { + proxy.abort(); + anyhow::bail!("无法启用本机代理:{error}"); + } + }; + ready(); + let result = tokio::time::timeout(Duration::from_secs(60), result).await; + drop(proxy_guard); + // Let the just-forwarded article response finish before aborting the listener. + let _ = shutdown_tx.send(()); + if tokio::time::timeout(Duration::from_secs(2), &mut proxy) + .await + .is_err() + { + proxy.abort(); + } + result + .context("60 秒内未收到该文章的互动数据。请在微信内打开或刷新原文后重试")? + .context("互动响应监听已结束") + } + + #[cfg(test)] + mod tests { + use super::*; + use serde_json::json; + + #[tokio::test] + async fn only_selected_article_and_valid_counts_are_accepted() { + let target = ArticleIdentity { + biz: "B==".into(), + mid: "42".into(), + idx: 2, + }; + let request = |query: &str| { + Request::post(format!("https://{HOST}/mp/getappmsgext?{query}")) + .header(header::USER_AGENT, "MicroMessenger") + .body(Body::empty()) + .unwrap() + }; + assert_eq!( + target.response_kind(&request("__biz=B%3D%3D&mid=42&idx=2")), + Some(ArticleResponse::Stats) + ); + assert_eq!( + target.response_kind(&request("__biz=B%3D%3D&mid=42&idx=1")), + None + ); + assert_eq!( + target.response_kind(&request("__biz=B%3D%3D&mid=42&idx=2&idx=2")), + None + ); + + let (sender, mut receiver) = oneshot::channel(); + let handler = Handler::new(target, sender); + let body = json!({"base_resp":{"ret":-1},"comment_count":0}).to_string(); + handler + .observe(Response::new(Body::from(body)), ArticleResponse::Stats) + .await; + assert!(receiver.try_recv().is_err()); + let body = json!({"appmsgstat":{"old_like_num":"8"},"comment_count":0}).to_string(); + let returned = handler + .observe( + Response::new(Body::from(body.clone())), + ArticleResponse::Stats, + ) + .await; + assert_eq!( + returned + .into_body() + .collect() + .await + .unwrap() + .to_bytes() + .as_ref(), + body.as_bytes() + ); + let counts = receiver.await.unwrap(); + assert_eq!(counts.comment_count, Some(0)); + assert_eq!(counts.like_count, Some(8)); + assert_eq!(counts.read_count, None); + } + + #[tokio::test] + async fn selected_article_page_returns_current_embedded_counts() { + let target = ArticleIdentity { + biz: "B==".into(), + mid: "42".into(), + idx: 2, + }; + let request = Request::get("https://mp.weixin.qq.com/s?__biz=B%3D%3D&mid=42&idx=2") + .header(header::USER_AGENT, "MicroMessenger") + .body(Body::empty()) + .unwrap(); + assert_eq!(target.response_kind(&request), Some(ArticleResponse::Page)); + let (sender, receiver) = oneshot::channel(); + let handler = Handler::new(target, sender); + let page = r#"
comment_count: 999
+ + "#; + let returned = handler + .observe(Response::new(Body::from(page)), ArticleResponse::Page) + .await; + assert_eq!( + returned + .into_body() + .collect() + .await + .unwrap() + .to_bytes() + .as_ref(), + page.as_bytes() + ); + let counts = receiver.await.unwrap(); + assert_eq!(counts.read_count, Some(97794)); + assert_eq!(counts.comment_count, Some(54)); + assert_eq!(counts.like_count, None); + assert!( + ArticleInteractions::parse_html("").is_none() + ); + } + + #[tokio::test] + async fn missing_article_does_not_start_a_proxy() { + let store = crate::Store::open_in_memory().unwrap(); + let ca = crate::ca::CaMaterial::generate().unwrap(); + let error = super::super::collect::<()>( + &store, + 42, + ca, + |_| panic!("unexpected proxy setup"), + || panic!("unexpected ready notification"), + ) + .await + .unwrap_err(); + assert_eq!(error.to_string(), "文章不存在"); + } + + #[test] + fn metrics_updates_keep_previous_fields_when_missing() { + let store = crate::Store::open_in_memory().unwrap(); + let id = store + .upsert_article("B", "42", 1, &crate::ArticleFields::default()) + .unwrap(); + store + .save_article_interactions( + id, + &ArticleInteractions { + read_count: Some(20), + comment_count: Some(5), + ..Default::default() + }, + ) + .unwrap(); + store + .save_article_interactions( + id, + &ArticleInteractions { + comment_count: Some(0), + ..Default::default() + }, + ) + .unwrap(); + let rows = store.list_articles(None, 10, 0, false).unwrap(); + assert_eq!(rows[0].interactions.read_count, Some(20)); + assert_eq!(rows[0].interactions.comment_count, Some(0)); + assert_eq!(rows[0].interactions.like_count, None); + } + } +} + +#[cfg(any(windows, test))] +pub async fn collect( + store: &crate::Store, + id: i64, + ca: crate::ca::CaMaterial, + install_proxy: impl FnOnce(u16) -> std::result::Result, + ready: impl FnOnce(), +) -> anyhow::Result { + use anyhow::{ensure, Context}; + let (article, _) = store.get_article_md(id)?.context("文章不存在")?; + ensure!(article.is_deleted == 0, "文章已删除"); + let target = capture::ArticleIdentity { + biz: article.biz, + mid: article + .mid + .filter(|mid| !mid.is_empty()) + .context("文章缺少消息 ID")?, + idx: article.idx.filter(|idx| *idx > 0).context("文章缺少序号")?, + }; + let metrics = capture::run(ca, target, install_proxy, ready).await?; + store.save_article_interactions(id, &metrics)?; + Ok(metrics) +} diff --git a/crates/core/src/workbench/mod.rs b/crates/core/src/workbench/mod.rs index cfb93f2..1e335b7 100644 --- a/crates/core/src/workbench/mod.rs +++ b/crates/core/src/workbench/mod.rs @@ -3,6 +3,7 @@ pub mod archive; pub mod discovery; pub mod engine; mod export_html; +pub mod interactions; pub mod markdown_export; pub mod push_monitor; mod request; diff --git a/frontend/src/lib/tauri.ts b/frontend/src/lib/tauri.ts index 97ad978..3105152 100644 --- a/frontend/src/lib/tauri.ts +++ b/frontend/src/lib/tauri.ts @@ -163,7 +163,15 @@ export interface SystemStatus { } /** 「公众号文章」列表行(后端 ArticleItem)。 */ +export interface ArticleInteractions { + read_count: number | null; + like_count: number | null; + watching_count: number | null; + comment_count: number | null; +} + export interface ArticleItem { + interactions: ArticleInteractions; has_body: boolean; id: number; biz: string; diff --git a/frontend/src/lib/workbench.ts b/frontend/src/lib/workbench.ts index 9ac1942..fff3da7 100644 --- a/frontend/src/lib/workbench.ts +++ b/frontend/src/lib/workbench.ts @@ -118,3 +118,9 @@ export const logUiError = (kind: "uncaught_error" | "unhandled_rejection" | "act export const exportExperiment = (id: number) => invoke<{ path: string; count: number } | null>("workbench_export_experiment", { id }); export const articleBodyStates = (articleIds: number[]) => invoke>("workbench_article_body_states", { articleIds }); + +export async function collectArticleInteractions(articleId: number, onReady: () => void) { + const ready = new Channel(); + ready.onmessage = onReady; + return invoke("workbench_collect_interactions", { articleId, onReady: ready }); +} diff --git a/frontend/src/views/Workbench.tsx b/frontend/src/views/Workbench.tsx index e8601c6..013597d 100644 --- a/frontend/src/views/Workbench.tsx +++ b/frontend/src/views/Workbench.tsx @@ -24,8 +24,8 @@ import { canCancelTask, sourceBodyAction } from "@/lib/action-visibility"; import { relativeTime } from "@/lib/relative-time"; import { recoveryIsWaiting, recoveryMessage } from "@/lib/home-sync"; import { Popover, PopoverTrigger, PopoverContent, PopoverClose } from "@/components/ui/popover"; -import { coreHealth, nativeEnvironment, getArticleDetail, openExternal, listArticles, articleSelectionIds, listAccounts, revealInFolder, listLogs, sysproxyResetStale, DEFAULT_CFG } from "@/lib/tauri"; -import { logUiError, workbenchSnapshot, articleBodyStates, sourcePage, taskPage, requestPage, downloadArticles, exportArticles, deleteArticles, deleteSource, downloadSourceBodies, exportSourceArticles, syncSourceHome, createHistory, readArchive, savePolicy, exportRequests, pythonPath, type Policy, type Task, type DownloadReceipt, type MarkdownExport } from "@/lib/workbench"; +import { certStatus, installCert, coreHealth, nativeEnvironment, getArticleDetail, openExternal, listArticles, articleSelectionIds, listAccounts, revealInFolder, listLogs, sysproxyResetStale, DEFAULT_CFG } from "@/lib/tauri"; +import { collectArticleInteractions, logUiError, workbenchSnapshot, articleBodyStates, sourcePage, taskPage, requestPage, downloadArticles, exportArticles, deleteArticles, deleteSource, downloadSourceBodies, exportSourceArticles, syncSourceHome, createHistory, readArchive, savePolicy, exportRequests, pythonPath, type Policy, type Task, type DownloadReceipt, type MarkdownExport } from "@/lib/workbench"; const selectClass = "h-9 rounded-md border border-input bg-background px-3 text-sm"; const names: Record = { @@ -169,6 +169,12 @@ function showExportResult(result: MarkdownExport | null) { } export function WorkbenchArticles({biz,onBizChange}:{biz:string;onBizChange:(biz:string)=>void}) { const snapshot = useSnapshot(); const { busy, run } = useAction(); + const health = useQuery({ queryKey: ["health"], queryFn: coreHealth }); + const [interaction, setInteraction] = useState<{ id: number; url: string; title: string } | null>(null); + const interactionCert = useQuery({ queryKey: ["interaction-certificate"], queryFn: certStatus, enabled: interaction !== null }); + const canCollectInteraction = interactionCert.data?.installed && interactionCert.data.ca_exists; + const [interactionReady, setInteractionReady] = useState(false); + const [collectingInteraction, setCollectingInteraction] = useState(false); const [page, setPage] = useState(0); const [pageSize,setPageSize]=useState(DEFAULT_PAGE_SIZE); const [selected, setSelected] = useState([]); const [deleting, setDeleting] = useState(null); const [reader, setReader] = useState<{ title: string; html?: string; markdown?: string } | null>(null); @@ -202,13 +208,61 @@ export function WorkbenchArticles({biz,onBizChange}:{biz:string;onBizChange:(biz {selected.length > 0 &&
已选择 {selected.length} 篇{selectionReady ? : null}{missingSelected.length > 0 ? : !selectionReady ? {selectedStates.error ? "正文状态读取失败,请重试" : "正在检查正文状态…"} : null}
} {articles.error &&

文章读取失败:{String(articles.error)}

} - selected.includes(a.id))} onChange={() => setSelected(old => rows.every(a => old.includes(a.id)) ? old.filter(id => !rows.some(a => a.id === id)) : Array.from(new Set([...old, ...rows.map(a => a.id)])))} />{["文章", "发布时间", "操作"].map(h => {h})}{rows.map(a => - setSelected(old => toggle(old, a.id))} />

{a.title || "无标题"}

{a.account || a.author || ""}

{dt(a.published_at)}
+
selected.includes(a.id))} onChange={() => setSelected(old => rows.every(a => old.includes(a.id)) ? old.filter(id => !rows.some(a => a.id === id)) : Array.from(new Set([...old, ...rows.map(a => a.id)])))} />{["文章", "发布时间", "互动", "操作"].map(h => {h})}{rows.map(a => + setSelected(old => toggle(old, a.id))} />

{a.title || "无标题"}

{a.account || a.author || ""}

{dt(a.published_at)} + + {Object.values(a.interactions).every(value => value == null) + ? 待补采 + :
+ 阅读 {a.interactions.read_count ?? "—"} + 点赞 {a.interactions.like_count ?? "—"} + 在看 {a.interactions.watching_count ?? "—"} + 评论 {a.interactions.comment_count ?? "—"} +
} +
{a.has_body ? <> run(() => read(a.id))}>阅读 run(async () => showExportResult(await exportArticles([a.id])))}>导出 : run(async () => showDownloadReceipt(await downloadArticles([a.id])))}>下载} + {health.data?.platform === "windows" && a.content_url && { + setInteractionReady(false); + setInteraction({ id: a.id, url: a.content_url!, title: a.title || "无标题" }); + }}>补采互动} {a.content_url && run(() => openExternal(a.content_url!))}>查看原文}
)}
{!rows.length && {articles.isPending ? "正在读取文章…" : "尚无文章。请先获取公众号第一页。"}} {setPageSize(size);setPage(0);}} />
+ { if (!open && !collectingInteraction) setInteraction(null); }}> + + + 补采互动 · {interaction?.title} + 准备文章链接。开始后,请在 60 秒内用桌面微信打开或刷新这篇文章。 + + event.currentTarget.select()} /> +

+ {interactionReady ? "正在等候微信返回阅读、点赞、在看和评论数。" : collectingInteraction ? "正在准备监听…" : "此功能临时使用 MPider 本地代理。首次使用时需要安装并信任 MPider 证书。"} +

+
+ {interactionCert.isError && } + {!canCollectInteraction && interactionCert.isSuccess && } + + +
+
+
{ if (!open) setReader(null); }}>{reader?.title}阅读本地正文;未保存的远程图片不会自动加载。{reader?.html ?