252 lines
6.7 KiB
TypeScript
Raw Normal View History

2023-08-01 21:35:21 +02:00
import { Handlers } from "$fresh/server.ts";
import { Readability } from "https://cdn.skypack.dev/@mozilla/readability";
2025-01-18 00:46:05 +01:00
import { DOMParser } from "domparser";
2023-08-04 22:35:25 +02:00
import { AccessDeniedError, BadRequestError } from "@lib/errors.ts";
import { createStreamResponse, isValidUrl } from "@lib/helpers.ts";
2023-08-01 21:35:21 +02:00
import * as openai from "@lib/openai.ts";
2025-01-05 14:59:05 +01:00
import tds from "https://cdn.skypack.dev/turndown@7.2.0";
import { Article, createArticle } from "@lib/resource/articles.ts";
import { getYoutubeVideoDetails } from "@lib/youtube.ts";
2023-08-04 22:35:25 +02:00
import { extractYoutubeId, isYoutubeLink } from "@lib/string.ts";
import { createLogger } from "@lib/log/index.ts";
2023-08-01 21:35:21 +02:00
const parser = new DOMParser();
2023-08-05 22:16:14 +02:00
const log = createLogger("api/article");
2023-08-01 21:35:21 +02:00
async function processCreateArticle(
{ fetchUrl, streamResponse }: {
fetchUrl: string;
streamResponse: ReturnType<typeof createStreamResponse>;
},
) {
2023-08-05 22:16:14 +02:00
log.info("create article from url", { url: fetchUrl });
2023-08-01 21:35:21 +02:00
streamResponse.enqueue("downloading article");
const request = await fetch(fetchUrl);
const html = await request.text();
streamResponse.enqueue("download success");
const document = parser.parseFromString(html, "text/html");
const title = document?.querySelector("title")?.innerText;
2023-08-04 22:35:25 +02:00
const images: HTMLImageElement[] = [];
document?.querySelectorAll("img").forEach((img) => {
images.push(img as unknown as HTMLImageElement);
});
const metaAuthor =
document?.querySelector('meta[name="twitter:creator"]')?.getAttribute(
"content",
) ||
document?.querySelector('meta[name="author"]')?.getAttribute("content");
const readable = new Readability(document);
const result = readable.parse();
2023-08-05 22:16:14 +02:00
log.debug("parsed", {
url: fetchUrl,
content: result.textContent,
});
const cleanDocument = parser.parseFromString(
result.content,
"text/html",
);
const service = new tds({
headingStyle: "atx",
codeBlockStyle: "fenced",
hr: "---",
bulletListMarker: "-",
});
2023-08-01 21:35:21 +02:00
const url = new URL(fetchUrl);
2023-08-04 22:35:25 +02:00
function makeUrlAbsolute(src: string) {
if (src.startsWith("/")) {
return `${url.origin}${src.replace(/$\//, "")}`;
}
if (!src.startsWith("https://") && !src.startsWith("http://")) {
return `${url.origin.replace(/\/$/, "")}/${src.replace(/^\//, "")})`;
}
return src;
}
service.addRule("fix image links", {
filter: ["img"],
replacement: function (_: string, node: HTMLImageElement) {
const src = node.getAttribute("src");
const alt = node.getAttribute("alt") || "";
if (!src || src.startsWith("data:image")) return "";
2023-08-01 21:35:21 +02:00
2023-08-04 22:35:25 +02:00
return `![${alt}](${makeUrlAbsolute(src)})`;
},
});
service.addRule("fix normal links", {
filter: ["a"],
replacement: function (content: string, node: HTMLImageElement) {
const href = node.getAttribute("href");
if (!href) return content;
2023-08-01 21:35:21 +02:00
if (href.startsWith("/")) {
return `[${content}](${url.origin}${href.replace(/$\//, "")})`;
}
2023-08-01 21:35:21 +02:00
if (href.startsWith("#")) {
if (content.length < 2) return "";
return `[${content}](${url.href}#${href})`.replace("##", "#");
}
2023-08-01 21:35:21 +02:00
if (!href.startsWith("https://") && !href.startsWith("http://")) {
return `[${content}](${url.origin.replace(/\/$/, "")}/${
href.replace(/^\//, "")
})`;
}
return `[${content}](${href})`;
},
});
2023-08-01 21:35:21 +02:00
const markdown = service.turndown(cleanDocument);
streamResponse.enqueue("parsed article, creating tags with openai");
const [tags, shortTitle, author] = await Promise.all([
openai.createTags(markdown),
title && openai.shortenTitle(title),
metaAuthor || openai.extractAuthorName(markdown),
]);
const id = shortTitle || title || "";
2023-08-04 22:35:25 +02:00
const meta: Article["meta"] = {
author: (author || "").replace("@", "twitter:"),
link: fetchUrl,
done: false,
2023-08-04 22:35:25 +02:00
date: new Date(),
};
const largestImage = images.filter((img) => {
const src = img.getAttribute("src");
return !!src && !src.startsWith("data:");
}).sort((a, b) => {
const aSize = +(a.getAttribute("width") || 0) +
+(a.getAttribute("height") || 0);
const bSize = +(b.getAttribute("width") || 0) +
+(b.getAttribute("height") || 0);
return aSize > bSize ? -1 : 1;
})[0];
const newArticle = {
2023-08-04 22:35:25 +02:00
type: "article",
id,
name: title || "",
content: markdown,
tags: tags || [],
2023-08-04 22:35:25 +02:00
meta,
} as const;
2023-08-04 22:35:25 +02:00
if (largestImage) {
const src = makeUrlAbsolute(largestImage.getAttribute("src") || "");
if (src) {
meta.image = src;
}
}
streamResponse.enqueue("finished processing");
await createArticle(newArticle.id, newArticle);
streamResponse.enqueue("id: " + newArticle.id);
}
async function processCreateYoutubeVideo(
{ fetchUrl, streamResponse }: {
fetchUrl: string;
streamResponse: ReturnType<typeof createStreamResponse>;
},
) {
2023-08-05 22:16:14 +02:00
log.info("create youtube article from url", {
url: fetchUrl,
});
streamResponse.enqueue("getting video infos from youtube api");
const id = extractYoutubeId(fetchUrl);
const video = await getYoutubeVideoDetails(id);
streamResponse.enqueue("shortening title with openai");
const newId = await openai.shortenTitle(video.snippet.title);
const newArticle: Article = {
2023-08-05 22:16:14 +02:00
type: "article",
name: video.snippet.title,
id: newId || video.snippet.title,
content: video.snippet.description,
tags: video.snippet?.tags?.slice(0, 5) || [],
meta: {
done: false,
link: fetchUrl,
author: video.snippet.channelTitle,
date: new Date(video.snippet.publishedAt),
},
};
streamResponse.enqueue("creating article");
await createArticle(newArticle.id, newArticle);
streamResponse.enqueue("finished");
streamResponse.enqueue("id: " + newArticle.id);
}
export const handler: Handlers = {
2023-08-04 22:35:25 +02:00
GET(req, ctx) {
const session = ctx.state.session;
if (!session) {
throw new AccessDeniedError();
}
const url = new URL(req.url);
const fetchUrl = url.searchParams.get("url");
if (!fetchUrl || !isValidUrl(fetchUrl)) {
throw new BadRequestError();
}
2023-08-01 21:35:21 +02:00
const streamResponse = createStreamResponse();
2023-08-01 21:35:21 +02:00
if (isYoutubeLink(fetchUrl)) {
processCreateYoutubeVideo({ fetchUrl, streamResponse }).then(
(article) => {
2023-08-05 22:16:14 +02:00
log.debug("created article from youtube", { article });
},
).catch((err) => {
2023-08-05 22:16:14 +02:00
log.error(err);
}).finally(() => {
streamResponse.cancel();
});
} else {
processCreateArticle({ fetchUrl, streamResponse }).then((article) => {
2023-08-05 22:16:14 +02:00
log.debug("created article from link", { article });
}).catch((err) => {
2023-08-05 22:16:14 +02:00
log.error(err);
}).finally(() => {
streamResponse.cancel();
});
}
2023-08-01 21:35:21 +02:00
return streamResponse.response;
2023-08-01 21:35:21 +02:00
},
};