* init * fix: electron Signed-off-by: Innei <i@innei.in> * update Signed-off-by: Innei <i@innei.in> * fix: build Signed-off-by: Innei <i@innei.in> * fix: lint Signed-off-by: Innei <i@innei.in> * fix: test Signed-off-by: Innei <i@innei.in> --------- Signed-off-by: Innei <i@innei.in>
45 lines
1.3 KiB
TypeScript
45 lines
1.3 KiB
TypeScript
import { Readability } from "@mozilla/readability"
|
|
import { name, version } from "@pkg"
|
|
import { parseHTML } from "linkedom"
|
|
import { fetch } from "ofetch"
|
|
|
|
import { isDev } from "../env"
|
|
|
|
const userAgents = `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36 ${name}/${version}`
|
|
|
|
export async function readability(url: string) {
|
|
const documentString = await fetch(url, {
|
|
headers: {
|
|
"User-Agent": userAgents,
|
|
},
|
|
}).then((res) => res.text())
|
|
|
|
// FIXME: linkedom does not handle relative addresses in strings. Refer to
|
|
// @see https://github.com/WebReflection/linkedom/issues/153
|
|
// JSDOM handles it correctly, but JSDOM introduces canvas binding.
|
|
|
|
const { document } = parseHTML(documentString)
|
|
const baseUrl = new URL(url).origin
|
|
|
|
document.querySelectorAll("a").forEach((a) => {
|
|
a.href = replaceRelativeAddress(baseUrl, a.href)
|
|
})
|
|
;(["img", "audio", "video"] as const).forEach((tag) => {
|
|
document.querySelectorAll(tag).forEach((img) => {
|
|
img.src = img.src && replaceRelativeAddress(baseUrl, img.src)
|
|
})
|
|
})
|
|
|
|
const reader = new Readability(document, {
|
|
debug: isDev,
|
|
})
|
|
return reader.parse()
|
|
}
|
|
|
|
const replaceRelativeAddress = (baseUrl: string, url: string) => {
|
|
if (url.startsWith("http")) {
|
|
return url
|
|
}
|
|
return new URL(url, baseUrl).href
|
|
}
|