318 lines
8.4 KiB
TypeScript
318 lines
8.4 KiB
TypeScript
|
|
import { requestUrl } from "obsidian";
|
|||
|
|
import { Readability } from "@mozilla/readability";
|
|||
|
|
import TurndownService from "turndown";
|
|||
|
|
// turndown-plugin-gfm 没带类型声明,这里按 CommonJS 具名导入
|
|||
|
|
// @ts-ignore
|
|||
|
|
import { gfm } from "turndown-plugin-gfm";
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 全文抓取
|
|||
|
|
*
|
|||
|
|
* 列表和分类全部来自网站(网站已经抓好 RSS),只有「点开某一篇」时才来这里:
|
|||
|
|
* 1. 用 Obsidian 的 requestUrl 取原文 HTML(走主进程,没有 CORS)
|
|||
|
|
* 2. Readability 抽正文(失败就退回「找 article/main/正文容器」的兜底)
|
|||
|
|
* 3. Turndown 转 Markdown,交给阅读窗口渲染,也能直接存成笔记
|
|||
|
|
*/
|
|||
|
|
|
|||
|
|
export interface ExtractedArticle {
|
|||
|
|
url: string;
|
|||
|
|
title: string;
|
|||
|
|
byline: string;
|
|||
|
|
siteName: string;
|
|||
|
|
excerpt: string;
|
|||
|
|
publishedTime: string;
|
|||
|
|
markdown: string;
|
|||
|
|
charCount: number;
|
|||
|
|
usedFallback: boolean;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/** 正文太少时判定「没抽到」,交给 UI 提示去浏览器看 */
|
|||
|
|
export class NoContentError extends Error {
|
|||
|
|
constructor(message: string) {
|
|||
|
|
super(message);
|
|||
|
|
this.name = "NoContentError";
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
let turndownService: TurndownService | null = null;
|
|||
|
|
|
|||
|
|
function turndown(): TurndownService {
|
|||
|
|
if (turndownService) return turndownService;
|
|||
|
|
|
|||
|
|
const service = new TurndownService({
|
|||
|
|
headingStyle: "atx",
|
|||
|
|
codeBlockStyle: "fenced",
|
|||
|
|
bulletListMarker: "-",
|
|||
|
|
emDelimiter: "*",
|
|||
|
|
hr: "---",
|
|||
|
|
linkStyle: "inlined",
|
|||
|
|
});
|
|||
|
|
|
|||
|
|
service.use(gfm);
|
|||
|
|
|
|||
|
|
// 代码块里的行号、复制按钮这类装饰性节点会被转成乱码,直接丢掉
|
|||
|
|
service.remove(["script", "style", "noscript", "form", "button"]);
|
|||
|
|
|
|||
|
|
turndownService = service;
|
|||
|
|
|
|||
|
|
return service;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/** 把相对链接 / 懒加载图片全部改成绝对地址,Markdown 里才不会出现 404 图片 */
|
|||
|
|
function absolutize(doc: Document, baseUrl: string): void {
|
|||
|
|
const fix = (selector: string, attr: string) => {
|
|||
|
|
doc.querySelectorAll(selector).forEach((node) => {
|
|||
|
|
const el = node as HTMLElement;
|
|||
|
|
const raw = el.getAttribute(attr);
|
|||
|
|
|
|||
|
|
if (!raw) return;
|
|||
|
|
|
|||
|
|
const value = raw.trim();
|
|||
|
|
|
|||
|
|
if (value === "" || value.startsWith("data:") || value.startsWith("#")) return;
|
|||
|
|
|
|||
|
|
try {
|
|||
|
|
el.setAttribute(attr, new URL(value, baseUrl).href);
|
|||
|
|
} catch (error) {
|
|||
|
|
/* 拼不出绝对地址就保留原样 */
|
|||
|
|
}
|
|||
|
|
});
|
|||
|
|
};
|
|||
|
|
|
|||
|
|
fix("a[href]", "href");
|
|||
|
|
fix("img[src]", "src");
|
|||
|
|
fix("source[src]", "src");
|
|||
|
|
fix("video[src]", "src");
|
|||
|
|
|
|||
|
|
// 懒加载:src 常常是先放一张占位图,真地址在 data-src / data-original / data-actualsrc
|
|||
|
|
doc.querySelectorAll("img").forEach((node) => {
|
|||
|
|
const img = node as HTMLImageElement;
|
|||
|
|
const lazy =
|
|||
|
|
img.getAttribute("data-src") ||
|
|||
|
|
img.getAttribute("data-original") ||
|
|||
|
|
img.getAttribute("data-actualsrc") ||
|
|||
|
|
img.getAttribute("data-lazy-src");
|
|||
|
|
|
|||
|
|
if (!lazy) return;
|
|||
|
|
|
|||
|
|
try {
|
|||
|
|
img.setAttribute("src", new URL(lazy.trim(), baseUrl).href);
|
|||
|
|
} catch (error) {
|
|||
|
|
/* 忽略 */
|
|||
|
|
}
|
|||
|
|
});
|
|||
|
|
|
|||
|
|
// srcset 里往往是 2x 图,正文里用不到,留着会让 Readability 选错尺寸
|
|||
|
|
doc.querySelectorAll("img").forEach((node) => node.removeAttribute("srcset"));
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
const JUNK_SELECTORS = [
|
|||
|
|
"script",
|
|||
|
|
"style",
|
|||
|
|
"noscript",
|
|||
|
|
"iframe",
|
|||
|
|
"form",
|
|||
|
|
"nav",
|
|||
|
|
"aside",
|
|||
|
|
"footer",
|
|||
|
|
"header",
|
|||
|
|
".sidebar",
|
|||
|
|
".comments",
|
|||
|
|
".comment",
|
|||
|
|
"#comments",
|
|||
|
|
".share",
|
|||
|
|
".social",
|
|||
|
|
".related",
|
|||
|
|
".advertisement",
|
|||
|
|
".ads",
|
|||
|
|
".breadcrumb",
|
|||
|
|
".pagination",
|
|||
|
|
".post-navigation",
|
|||
|
|
".widget",
|
|||
|
|
".menu",
|
|||
|
|
".toolbar",
|
|||
|
|
];
|
|||
|
|
|
|||
|
|
/** Readability 抽不出来时的兜底:找最像正文的容器再洗一遍 */
|
|||
|
|
function fallbackHtml(doc: Document): string {
|
|||
|
|
const candidates = [
|
|||
|
|
"article",
|
|||
|
|
"main",
|
|||
|
|
"[role=main]",
|
|||
|
|
".post-content",
|
|||
|
|
".entry-content",
|
|||
|
|
".article-content",
|
|||
|
|
".content",
|
|||
|
|
"#content",
|
|||
|
|
"body",
|
|||
|
|
];
|
|||
|
|
|
|||
|
|
let target: Element | null = null;
|
|||
|
|
let bestLength = 0;
|
|||
|
|
|
|||
|
|
for (const selector of candidates) {
|
|||
|
|
doc.querySelectorAll(selector).forEach((node) => {
|
|||
|
|
const textLength = (node.textContent || "").replace(/\s+/g, "").length + (node.querySelectorAll("p").length > 3 ? 500 : 0);
|
|||
|
|
|
|||
|
|
if (textLength > bestLength) {
|
|||
|
|
bestLength = textLength;
|
|||
|
|
target = node;
|
|||
|
|
}
|
|||
|
|
});
|
|||
|
|
|
|||
|
|
if (target && bestLength > 400) break;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
const container = target || doc.body;
|
|||
|
|
|
|||
|
|
if (!container) return "";
|
|||
|
|
|
|||
|
|
const copy = container.cloneNode(true) as Element;
|
|||
|
|
|
|||
|
|
JUNK_SELECTORS.forEach((selector) => {
|
|||
|
|
copy.querySelectorAll(selector).forEach((node) => node.parentNode?.removeChild(node));
|
|||
|
|
});
|
|||
|
|
|
|||
|
|
// 一堆空 div / span 会被 Turndown 转成大量空行
|
|||
|
|
copy.querySelectorAll("div, span, section").forEach((node) => {
|
|||
|
|
if ((node.textContent || "").trim() === "" && node.querySelectorAll("img, video").length === 0) {
|
|||
|
|
node.parentNode?.removeChild(node);
|
|||
|
|
}
|
|||
|
|
});
|
|||
|
|
|
|||
|
|
return copy.innerHTML;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
function cleanMarkdown(markdown: string): string {
|
|||
|
|
return String(markdown || "")
|
|||
|
|
.replace(/\r\n/g, "\n")
|
|||
|
|
.replace(/[ \t]+\n/g, "\n")
|
|||
|
|
.replace(/\n{3,}/g, "\n\n")
|
|||
|
|
.replace(/^\s+|\s+$/g, "");
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
|
|||
|
|
/** 标题里常带「 - 站点名 / | 站点名」,去掉尾巴,存成笔名时干净些 */
|
|||
|
|
function stripSiteSuffix(title: string, siteName: string, url: string): string {
|
|||
|
|
let value = String(title || "").trim();
|
|||
|
|
const names = [siteName, hostOf(url)].filter(Boolean);
|
|||
|
|
|
|||
|
|
for (const name of names) {
|
|||
|
|
const escaped = String(name).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|||
|
|
const re = new RegExp(`\\s*[\\-|—–_·::]\\s*${escaped}\\s*$`, "i");
|
|||
|
|
const next = value.replace(re, "").trim();
|
|||
|
|
|
|||
|
|
if (next !== "" && next !== value) {
|
|||
|
|
value = next;
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
return value;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
function meta(doc: Document, names: string[]): string {
|
|||
|
|
for (const name of names) {
|
|||
|
|
const el = doc.querySelector(`meta[property="${name}"], meta[name="${name}"]`);
|
|||
|
|
|
|||
|
|
if (el) {
|
|||
|
|
const content = (el.getAttribute("content") || "").trim();
|
|||
|
|
|
|||
|
|
if (content) return content;
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
return "";
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
function hostOf(url: string): string {
|
|||
|
|
try {
|
|||
|
|
return new URL(url).host;
|
|||
|
|
} catch (error) {
|
|||
|
|
return "";
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 抓一篇的全文
|
|||
|
|
*
|
|||
|
|
* @throws NoContentError 抽不到正文(原文结构特殊 / 需要登录 / 是纯图片)
|
|||
|
|
* @throws Error 网络或状态码问题
|
|||
|
|
*/
|
|||
|
|
export async function fetchFullText(url: string): Promise<ExtractedArticle> {
|
|||
|
|
const target = String(url || "").trim();
|
|||
|
|
|
|||
|
|
if (!/^https?:\/\//i.test(target)) {
|
|||
|
|
throw new Error(`文章链接不是 http/https:${target || "(空)"}`);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
const response = await requestUrl({
|
|||
|
|
url: target,
|
|||
|
|
method: "GET",
|
|||
|
|
throw: false,
|
|||
|
|
headers: {
|
|||
|
|
Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
|
|||
|
|
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
|
|||
|
|
// 有些站对空 UA 直接 403
|
|||
|
|
"User-Agent":
|
|||
|
|
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
|
|||
|
|
},
|
|||
|
|
});
|
|||
|
|
|
|||
|
|
if (response.status >= 400) {
|
|||
|
|
throw new Error(`原文返回 HTTP ${response.status},可能被防盗链或需要登录`);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
const html = String(response.text || "");
|
|||
|
|
|
|||
|
|
if (html.length < 200) {
|
|||
|
|
throw new NoContentError("原文内容为空(可能整页由脚本渲染)");
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
const doc = new DOMParser().parseFromString(html, "text/html");
|
|||
|
|
|
|||
|
|
absolutize(doc, target);
|
|||
|
|
|
|||
|
|
// Readability 会就地改写传入的文档,兜底要另一份
|
|||
|
|
const fallbackDoc = doc.cloneNode(true) as Document;
|
|||
|
|
|
|||
|
|
let parsed: any = null;
|
|||
|
|
|
|||
|
|
try {
|
|||
|
|
parsed = new Readability(doc, { charThreshold: 100 }).parse();
|
|||
|
|
} catch (error) {
|
|||
|
|
parsed = null;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
const usedFallback = !parsed || !parsed.content || String(parsed.content).length < 80;
|
|||
|
|
const htmlForMarkdown = usedFallback ? fallbackHtml(fallbackDoc) : String(parsed.content);
|
|||
|
|
const markdown = cleanMarkdown(turndown().turndown(htmlForMarkdown || ""));
|
|||
|
|
|
|||
|
|
const siteName = String((parsed && parsed.siteName) || meta(fallbackDoc, ["og:site_name"]) || hostOf(target)).trim();
|
|||
|
|
const rawTitle =
|
|||
|
|
(parsed && parsed.title) ||
|
|||
|
|
meta(fallbackDoc, ["og:title", "twitter:title"]) ||
|
|||
|
|
(fallbackDoc.title || "").trim() ||
|
|||
|
|
"未命名文章";
|
|||
|
|
const title = stripSiteSuffix(rawTitle, siteName, target) || rawTitle;
|
|||
|
|
|
|||
|
|
if (markdown.replace(/\s+/g, "").length < 40) {
|
|||
|
|
throw new NoContentError("没抽到正文");
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
const charCount = String((parsed && parsed.textContent) || fallbackDoc.body?.textContent || "")
|
|||
|
|
.replace(/\s+/g, "")
|
|||
|
|
.length;
|
|||
|
|
|
|||
|
|
return {
|
|||
|
|
url: target,
|
|||
|
|
title: title.trim(),
|
|||
|
|
byline: String((parsed && parsed.byline) || meta(fallbackDoc, ["author"]) || "").trim(),
|
|||
|
|
siteName,
|
|||
|
|
excerpt: String((parsed && parsed.excerpt) || meta(fallbackDoc, ["og:description", "description"]) || "").trim(),
|
|||
|
|
publishedTime: String((parsed && parsed.publishedTime) || meta(fallbackDoc, ["article:published_time"])) || "",
|
|||
|
|
markdown,
|
|||
|
|
charCount: charCount || markdown.replace(/\s+/g, "").length,
|
|||
|
|
usedFallback,
|
|||
|
|
};
|
|||
|
|
}
|