59 lines
2.1 KiB
TypeScript
59 lines
2.1 KiB
TypeScript
const SEARCH_TIMEOUT_MS = 10_000;
|
|
const MAX_RESULTS = 8;
|
|
|
|
export interface NewsArticle {
|
|
title: string;
|
|
url: string;
|
|
source: string;
|
|
publishedAt: string | null;
|
|
description: string;
|
|
}
|
|
|
|
function decodeXml(value: string): string {
|
|
return value
|
|
.replace(/<!\[CDATA\[([\s\S]*?)\]\]>/g, "$1")
|
|
.replace(/&/g, "&")
|
|
.replace(/</g, "<")
|
|
.replace(/>/g, ">")
|
|
.replace(/"/g, '"')
|
|
.replace(/'|'/g, "'")
|
|
.replace(/&#(\d+);/g, (_, code: string) => String.fromCodePoint(Math.min(Number(code), 0x10ffff)));
|
|
}
|
|
|
|
function field(item: string, name: string): string {
|
|
return decodeXml(item.match(new RegExp(`<${name}(?:\\s[^>]*)?>([\\s\\S]*?)<\\/${name}>`, "i"))?.[1] ?? "")
|
|
.replace(/<[^>]+>/g, " ")
|
|
.replace(/\s+/g, " ")
|
|
.trim();
|
|
}
|
|
|
|
/** Search current public news through Bing's RSS endpoint; no credentials or page data leave the server. */
|
|
export async function searchNews(query: string): Promise<NewsArticle[]> {
|
|
const url = new URL("https://www.bing.com/news/search");
|
|
url.searchParams.set("q", query);
|
|
url.searchParams.set("format", "rss");
|
|
url.searchParams.set("setlang", "th-TH");
|
|
const response = await fetch(url, {
|
|
cache: "no-store",
|
|
signal: AbortSignal.timeout(SEARCH_TIMEOUT_MS),
|
|
headers: { accept: "application/rss+xml,application/xml,text/xml", "user-agent": "PagivaContentResearch/1.0" },
|
|
});
|
|
if (!response.ok) throw new Error(`news search returned ${response.status}`);
|
|
const xml = await response.text();
|
|
return [...xml.matchAll(/<item>([\s\S]*?)<\/item>/gi)]
|
|
.map((match) => {
|
|
const item = match[1];
|
|
const rawDate = field(item, "pubDate");
|
|
const timestamp = Date.parse(rawDate);
|
|
return {
|
|
title: field(item, "title"),
|
|
url: field(item, "link"),
|
|
source: field(item, "News:Source") || field(item, "source") || "แหล่งข่าว",
|
|
publishedAt: Number.isNaN(timestamp) ? null : new Date(timestamp).toISOString(),
|
|
description: field(item, "description").slice(0, 600),
|
|
} satisfies NewsArticle;
|
|
})
|
|
.filter((article) => article.title && /^https?:\/\//.test(article.url))
|
|
.slice(0, MAX_RESULTS);
|
|
}
|