mirror of
https://github.com/BetterSEQTA/BetterSEQTA-Plus.git
synced 2026-12-06 19:56:45 +10:30
refactor: parse news feeds natively and raise safari minimum
This commit is contained in:
8 files changed
+287
-162
No files matched your search
Generated
-51
@@ -38,7 +38,6 @@
|
||||
"react": "^19.3.1",
|
||||
"react-best-gradient-color-picker": "^3.0.14",
|
||||
"react-dom": "^19.3.1",
|
||||
"rss-parser": "^3.13.0",
|
||||
"semver": "^7.7.1",
|
||||
"sortablejs": "^1.15.7",
|
||||
"svelte": "^5.57.3",
|
||||
@@ -9986,25 +9985,6 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/rss-parser": {
|
||||
"version": "3.13.0",
|
||||
"resolved": "https://registry.npmjs.org/rss-parser/-/rss-parser-3.13.0.tgz",
|
||||
"integrity": "sha512-7jWUBV5yGN3rqMMj7CZufl/291QAhvrrGpDNE4k/02ZchL0npisiYYqULF71jCEKoIiHvK/Q2e6IkDwPziT7+w==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"entities": "^2.0.3",
|
||||
"xml2js": "^0.5.0"
|
||||
}
|
||||
},
|
||||
"node_modules/rss-parser/node_modules/entities": {
|
||||
"version": "2.2.0",
|
||||
"resolved": "https://registry.npmjs.org/entities/-/entities-2.2.0.tgz",
|
||||
"integrity": "sha512-p92if5Nz619I0w+akJrLZH0MX0Pb5DX39XOwQTtXSdQQOaYH03S1uIQp4mhOZtAXrxq4ViO67YTiLBo2638o9A==",
|
||||
"license": "BSD-2-Clause",
|
||||
"funding": {
|
||||
"url": "https://github.com/fb55/entities?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/runed": {
|
||||
"version": "0.37.1",
|
||||
"resolved": "https://registry.npmjs.org/runed/-/runed-0.37.1.tgz",
|
||||
@@ -10076,15 +10056,6 @@
|
||||
"@parcel/watcher": "^2.4.1"
|
||||
}
|
||||
},
|
||||
"node_modules/sax": {
|
||||
"version": "1.6.1",
|
||||
"resolved": "https://registry.npmjs.org/sax/-/sax-1.6.1.tgz",
|
||||
"integrity": "sha512-42tBVwLWnaQvW5zc4HbZrTuWccECCZfBi92FDuwtqxasH+JbPB3/FOKb1m222K42R4WxuxzzMsTswfzgtSu64Q==",
|
||||
"license": "BlueOak-1.0.0",
|
||||
"engines": {
|
||||
"node": ">=11.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/saxes": {
|
||||
"version": "6.0.0",
|
||||
"resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz",
|
||||
@@ -11460,28 +11431,6 @@
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/xml2js": {
|
||||
"version": "0.5.0",
|
||||
"resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.5.0.tgz",
|
||||
"integrity": "sha512-drPFnkQJik/O+uPKpqSgr22mpuFHqKdbS835iAQrUC73L2F5WkboIRd63ai/2Yg6I1jzifPFKH2NTK+cfglkIA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"sax": ">=0.6.0",
|
||||
"xmlbuilder": "~11.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=4.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/xmlbuilder": {
|
||||
"version": "11.0.1",
|
||||
"resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-11.0.1.tgz",
|
||||
"integrity": "sha512-fDlsI/kFEx7gLvbecc0/ohLG50fugQp8ryHzMTuW9vSa1GJ0XYWKnhsUx7oie3G98+r56aTQIUB4kht42R3JvA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/xmlchars": {
|
||||
"version": "2.2.0",
|
||||
"resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz",
|
||||
|
||||
@@ -100,7 +100,6 @@
|
||||
"react": "^19.3.1",
|
||||
"react-best-gradient-color-picker": "^3.0.14",
|
||||
"react-dom": "^19.3.1",
|
||||
"rss-parser": "^3.13.0",
|
||||
"semver": "^7.7.1",
|
||||
"sortablejs": "^1.15.7",
|
||||
"svelte": "^5.57.3",
|
||||
|
||||
+1
-1
@@ -569,7 +569,7 @@ const MESSAGE_HANDLERS: Record<string, MessageHandler> = {
|
||||
sendResponse({ error: "Unauthorized sender" });
|
||||
return false;
|
||||
}
|
||||
fetchNews(req.source ?? "australia", sendResponse);
|
||||
void fetchNews(req.source).then((news) => sendResponse({ news }));
|
||||
return true;
|
||||
},
|
||||
fetchThemes: handleFetchThemes,
|
||||
|
||||
+49
-84
@@ -1,37 +1,18 @@
|
||||
import Parser from "rss-parser";
|
||||
import type { NewsFeed, NewsPayload } from "@/seqta/utils/newsFeed";
|
||||
|
||||
const NEWS_API_KEY = "17c0da766ba347c89d094449504e3080";
|
||||
const MAX_RATE_LIMIT_RETRIES = 3;
|
||||
|
||||
const fetchAustraliaNews = async (
|
||||
url: string,
|
||||
sendResponse: any,
|
||||
rateLimitRetryCount = 0,
|
||||
) => {
|
||||
fetch(url)
|
||||
.then((result) => result.json())
|
||||
.then((response) => {
|
||||
if (response.code == "rateLimited" && rateLimitRetryCount < MAX_RATE_LIMIT_RETRIES) {
|
||||
fetchAustraliaNews(`${url}%00`, sendResponse, rateLimitRetryCount + 1);
|
||||
} else {
|
||||
sendResponse({ news: response });
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error("[BetterSEQTA+] Failed to fetch Australia news", error);
|
||||
sendResponse({ news: { articles: [] } });
|
||||
});
|
||||
};
|
||||
const REQUEST_TIMEOUT_MS = 10_000;
|
||||
const DAY_MS = 86_400_000;
|
||||
|
||||
const rssFeedsByCountry: Record<string, string[]> = {
|
||||
usa: [
|
||||
"https://rss.nytimes.com/services/xml/rss/nyt/HomePage.xml",
|
||||
"https://www.huffpost.com/section/front-page/feed",
|
||||
"https://www.npr.org/rss/rss.php",
|
||||
"https://feeds.npr.org/1001/rss.xml",
|
||||
],
|
||||
taiwan: [
|
||||
"https://news.ltn.com.tw/rss/all.xml",
|
||||
"https://www.taipeitimes.com/xml/index.rss",
|
||||
"https://international.thenewslens.com/rss",
|
||||
],
|
||||
hong_kong: [
|
||||
"https://rthk9.rthk.hk/rthk/news/rss/e_expressnews_elocal.xml",
|
||||
@@ -41,87 +22,71 @@ const rssFeedsByCountry: Record<string, string[]> = {
|
||||
"https://critica.com.pa/rss.xml",
|
||||
"https://www.panamaamerica.com.pa/rss.xml",
|
||||
"https://noticiassin.com/feed/",
|
||||
"https://elcapitalfinanciero.com/feed/",
|
||||
],
|
||||
canada: [
|
||||
"https://www.cbc.ca/cmlink/rss-topstories",
|
||||
"https://calgaryherald.com/feed",
|
||||
"https://ottawacitizen.com/feed",
|
||||
"https://www.montrealgazette.com/feed",
|
||||
],
|
||||
singapore: [
|
||||
"https://www.straitstimes.com/news/singapore/rss.xml",
|
||||
"https://www.channelnewsasia.com/rssfeeds/8395986",
|
||||
],
|
||||
uk: [
|
||||
"http://feeds.bbci.co.uk/news/rss.xml",
|
||||
"https://feeds.bbci.co.uk/news/rss.xml",
|
||||
"https://www.theguardian.com/uk/rss",
|
||||
],
|
||||
japan: [
|
||||
"https://www3.nhk.or.jp/nhkworld/en/news/feeds/",
|
||||
"https://www3.nhk.or.jp/rss/news/cat0.xml",
|
||||
"https://news.livedoor.com/topics/rss/int.xml",
|
||||
],
|
||||
netherlands: ["https://www.dutchnews.nl/feed/", "https://www.nrc.nl/rss/"],
|
||||
};
|
||||
|
||||
export async function fetchNews(source: string | undefined, sendResponse: any) {
|
||||
const normalizedSource = typeof source === "string" && source.trim()
|
||||
? source.trim()
|
||||
: "australia";
|
||||
async function fetchAustraliaNews(): Promise<NewsPayload> {
|
||||
const from = new Date(Date.now() - 5 * DAY_MS).toISOString().slice(0, 10);
|
||||
let url = `https://newsapi.org/v2/everything?domains=abc.net.au&from=${from}&apiKey=${NEWS_API_KEY}`;
|
||||
|
||||
if (normalizedSource === "australia") {
|
||||
const date = new Date();
|
||||
date.setDate(date.getDate() - 5);
|
||||
|
||||
const from =
|
||||
date.getFullYear() +
|
||||
"-" +
|
||||
String(date.getMonth() + 1).padStart(2, "0") +
|
||||
"-" +
|
||||
String(date.getDate()).padStart(2, "0");
|
||||
|
||||
const url = `https://newsapi.org/v2/everything?domains=abc.net.au&from=${from}&apiKey=17c0da766ba347c89d094449504e3080`;
|
||||
fetchAustraliaNews(url, sendResponse);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const parser = new Parser();
|
||||
let feeds: string[];
|
||||
|
||||
if (rssFeedsByCountry[normalizedSource.toLowerCase()]) {
|
||||
feeds = rssFeedsByCountry[normalizedSource.toLowerCase()];
|
||||
} else if (normalizedSource.startsWith("http")) {
|
||||
feeds = [normalizedSource];
|
||||
} else {
|
||||
console.warn("[BetterSEQTA+] Invalid news source, falling back to Australia", normalizedSource);
|
||||
return fetchNews("australia", sendResponse);
|
||||
}
|
||||
|
||||
const articlesPromises = feeds.map(async (feedUrl) => {
|
||||
try {
|
||||
const response = await fetch(feedUrl);
|
||||
if (!response.ok) {
|
||||
console.error(`Failed to fetch RSS feed: ${feedUrl} (${response.status})`);
|
||||
return [];
|
||||
}
|
||||
const feedString = await response.text();
|
||||
const feed = await parser.parseString(feedString);
|
||||
|
||||
return feed.items.map((item) => ({
|
||||
title: item.title || "",
|
||||
description: item.contentSnippet || "",
|
||||
url: item.link || "",
|
||||
urlToImage: null,
|
||||
}));
|
||||
} catch (error) {
|
||||
console.error(`Failed to fetch RSS feed: ${feedUrl}`, error);
|
||||
return [];
|
||||
try {
|
||||
for (let attempt = 0; attempt <= MAX_RATE_LIMIT_RETRIES; attempt++) {
|
||||
const response = await fetch(url, { signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) });
|
||||
const data = await response.json();
|
||||
if (data.code !== "rateLimited") return { articles: data.articles ?? [] };
|
||||
url += "%00";
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("[BetterSEQTA+] Failed to fetch Australia news", error);
|
||||
}
|
||||
return { articles: [] };
|
||||
}
|
||||
|
||||
async function fetchFeed(url: string): Promise<NewsFeed> {
|
||||
const response = await fetch(url, { signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) });
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||
return { url: response.url || url, xml: await response.text() };
|
||||
}
|
||||
|
||||
function feedsForSource(source: string): string[] | null {
|
||||
const preset = rssFeedsByCountry[source.toLowerCase()];
|
||||
if (preset) return preset;
|
||||
return /^https?:\/\//i.test(source) ? [source] : null;
|
||||
}
|
||||
|
||||
export async function fetchNews(source?: string): Promise<NewsPayload> {
|
||||
const normalizedSource = source?.trim() || "australia";
|
||||
if (normalizedSource === "australia") return fetchAustraliaNews();
|
||||
|
||||
const articlesArray = await Promise.all(articlesPromises);
|
||||
const articles = articlesArray.flat();
|
||||
const feedUrls = feedsForSource(normalizedSource);
|
||||
if (!feedUrls) {
|
||||
console.warn("[BetterSEQTA+] Invalid news source, falling back to Australia", normalizedSource);
|
||||
return fetchAustraliaNews();
|
||||
}
|
||||
|
||||
sendResponse({ news: { articles } });
|
||||
const results = await Promise.allSettled(feedUrls.map(fetchFeed));
|
||||
const feeds = results.flatMap((result, i) => {
|
||||
if (result.status === "fulfilled") return [result.value];
|
||||
console.error(`[BetterSEQTA+] Failed to fetch RSS feed: ${feedUrls[i]}`, result.reason);
|
||||
return [];
|
||||
});
|
||||
return { feeds };
|
||||
}
|
||||
+16
-12
@@ -1,19 +1,23 @@
|
||||
import { createManifest } from "../../lib/createManifest.ts";
|
||||
import type { Manifest } from "../../lib/types.ts";
|
||||
import baseManifest from "./manifest.json" with { type: "json" };
|
||||
import pkg from "../../package.json" with { type: "json" };
|
||||
|
||||
const updatedSafariManifest = {
|
||||
...baseManifest,
|
||||
version: pkg.version,
|
||||
description: pkg.description,
|
||||
browser_specific_settings: {
|
||||
safari: {
|
||||
strict_min_version: "15.4",
|
||||
strict_max_version: "*",
|
||||
},
|
||||
// ^^^ https://developer.apple.com/documentation/safariservices/safari_web_extensions/optimizing_your_web_extension_for_safari#3743239
|
||||
// https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/browser_specific_settings#safari_properties
|
||||
type BrowserSpecificSettings = Extract<Manifest, { manifest_version: number }>["browser_specific_settings"];
|
||||
|
||||
const safariSettings = {
|
||||
safari: {
|
||||
strict_min_version: "17.4",
|
||||
strict_max_version: "*",
|
||||
},
|
||||
};
|
||||
|
||||
export const safari = createManifest(updatedSafariManifest, "safari");
|
||||
export const safari = createManifest(
|
||||
{
|
||||
...baseManifest,
|
||||
version: pkg.version,
|
||||
description: pkg.description,
|
||||
browser_specific_settings: safariSettings as unknown as BrowserSpecificSettings,
|
||||
},
|
||||
"safari",
|
||||
);
|
||||
@@ -7,6 +7,7 @@ import LogoLightOutline from "@/resources/icons/betterseqta-light-outline.png";
|
||||
import { resolveExtensionAssetUrl } from "@/lib/extensionAssetUrl";
|
||||
import { animate, stagger } from "motion";
|
||||
import { verboseInfo } from "@/utils/verboseLog";
|
||||
import { toNewsArticles, type NewsPayload } from "@/seqta/utils/newsFeed";
|
||||
import {
|
||||
applyPageFeatureGateEarly,
|
||||
injectPageFeatureBanner,
|
||||
@@ -67,12 +68,12 @@ export async function SendNewsPage() {
|
||||
const response = (await browser.runtime.sendMessage({
|
||||
type: "sendNews",
|
||||
source: settingsState.newsSource,
|
||||
})) as any;
|
||||
})) as { news?: NewsPayload } | undefined;
|
||||
const newscontainer = document.querySelector("#news-container");
|
||||
document.getElementById("newsloading")?.remove();
|
||||
|
||||
const articles = response?.news?.articles;
|
||||
if (!Array.isArray(articles) || articles.length === 0) {
|
||||
const articles = toNewsArticles(response?.news);
|
||||
if (articles.length === 0) {
|
||||
const emptyState = document.createElement("div");
|
||||
emptyState.classList.add("day-empty");
|
||||
const img = document.createElement("img");
|
||||
@@ -86,7 +87,7 @@ export async function SendNewsPage() {
|
||||
|
||||
const fragment = document.createDocumentFragment();
|
||||
|
||||
articles.forEach((article: any) => {
|
||||
for (const article of articles) {
|
||||
const newsarticle = document.createElement("a");
|
||||
newsarticle.classList.add("NewsArticle");
|
||||
newsarticle.href = article.url;
|
||||
@@ -95,14 +96,14 @@ export async function SendNewsPage() {
|
||||
const articleimage = document.createElement("div");
|
||||
articleimage.classList.add("articleimage");
|
||||
|
||||
if (article.urlToImage == "null" || article.urlToImage == null) {
|
||||
if (article.imageUrl) {
|
||||
articleimage.style.backgroundImage = `url(${JSON.stringify(article.imageUrl)})`;
|
||||
} else {
|
||||
articleimage.style.cssText = `
|
||||
background-image: url(${resolveExtensionAssetUrl(LogoLightOutline)});
|
||||
width: 20%;
|
||||
margin: 0 7.5%;
|
||||
`;
|
||||
} else {
|
||||
articleimage.style.backgroundImage = `url(${article.urlToImage})`;
|
||||
}
|
||||
|
||||
const articletext = document.createElement("div");
|
||||
@@ -114,19 +115,16 @@ export async function SendNewsPage() {
|
||||
title.target = "_blank";
|
||||
|
||||
const description = document.createElement("p");
|
||||
const articleDescription = typeof article.description === "string"
|
||||
? article.description
|
||||
: "No description available.";
|
||||
|
||||
const articleDescription = article.description || "No description available.";
|
||||
description.textContent =
|
||||
articleDescription.length > 400
|
||||
? articleDescription.substring(0, 400) + "..."
|
||||
? `${articleDescription.slice(0, 400)}…`
|
||||
: articleDescription;
|
||||
|
||||
articletext.append(title, description);
|
||||
newsarticle.append(articleimage, articletext);
|
||||
fragment.append(newsarticle);
|
||||
});
|
||||
}
|
||||
|
||||
newscontainer?.append(fragment);
|
||||
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
/**
|
||||
* @jest-environment jsdom
|
||||
*/
|
||||
import { describe, expect, it } from "@jest/globals";
|
||||
import { parseFeed, toNewsArticles } from "./newsFeed";
|
||||
|
||||
const rss2 = `<?xml version="1.0"?>
|
||||
<rss version="2.0" xmlns:media="http://search.yahoo.com/mrss/" xmlns:content="http://purl.org/rss/1.0/modules/content/">
|
||||
<channel>
|
||||
<title>Example</title>
|
||||
<item>
|
||||
<title>Budget & tax</title>
|
||||
<link>https://example.com/budget</link>
|
||||
<description><![CDATA[<p>The <b>budget</b> passed.</p>]]></description>
|
||||
<media:thumbnail url="https://example.com/budget.jpg" />
|
||||
</item>
|
||||
<item>
|
||||
<title>Relative</title>
|
||||
<link>/relative</link>
|
||||
<description>Plain text</description>
|
||||
<enclosure url="https://example.com/photo.png" type="image/png" length="1" />
|
||||
</item>
|
||||
<item>
|
||||
<title>Bad link</title>
|
||||
<link>javascript:alert(1)</link>
|
||||
</item>
|
||||
</channel>
|
||||
</rss>`;
|
||||
|
||||
const atom = `<?xml version="1.0"?>
|
||||
<feed xmlns="http://www.w3.org/2005/Atom">
|
||||
<entry>
|
||||
<title type="html">Rain <em>today</em></title>
|
||||
<link rel="self" href="https://example.org/self" />
|
||||
<link rel="alternate" href="https://example.org/rain" />
|
||||
<summary type="html"><img src="https://example.org/rain.jpg">Heavy rain expected.</summary>
|
||||
</entry>
|
||||
</feed>`;
|
||||
|
||||
const rdf = `<?xml version="1.0"?>
|
||||
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns="http://purl.org/rss/1.0/">
|
||||
<item>
|
||||
<title>RDF item</title>
|
||||
<link>https://example.net/rdf</link>
|
||||
<description>From RSS 1.0</description>
|
||||
</item>
|
||||
</rdf:RDF>`;
|
||||
|
||||
describe("parseFeed", () => {
|
||||
it("parses RSS 2.0 items with media images and stripped HTML", () => {
|
||||
const articles = parseFeed(rss2, "https://example.com/feed.xml");
|
||||
expect(articles).toEqual([
|
||||
{
|
||||
title: "Budget & tax",
|
||||
description: "The budget passed.",
|
||||
url: "https://example.com/budget",
|
||||
imageUrl: "https://example.com/budget.jpg",
|
||||
},
|
||||
{
|
||||
title: "Relative",
|
||||
description: "Plain text",
|
||||
url: "https://example.com/relative",
|
||||
imageUrl: "https://example.com/photo.png",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("parses Atom entries using the alternate link and inline images", () => {
|
||||
expect(parseFeed(atom)).toEqual([
|
||||
{
|
||||
title: "Rain today",
|
||||
description: "Heavy rain expected.",
|
||||
url: "https://example.org/rain",
|
||||
imageUrl: "https://example.org/rain.jpg",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("parses RSS 1.0 (RDF) items", () => {
|
||||
expect(parseFeed(rdf)[0]).toMatchObject({ title: "RDF item", url: "https://example.net/rdf" });
|
||||
});
|
||||
|
||||
it("returns nothing for invalid XML", () => {
|
||||
expect(parseFeed("<rss><channel><item>")).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("toNewsArticles", () => {
|
||||
it("normalises NewsAPI articles and drops unsafe links and images", () => {
|
||||
expect(
|
||||
toNewsArticles({
|
||||
articles: [
|
||||
{ title: "Good", description: null, url: "https://abc.net.au/a", urlToImage: "https://abc.net.au/a.jpg" },
|
||||
{ title: "Bad", url: "javascript:alert(1)" },
|
||||
{ title: "No image", url: "https://abc.net.au/b", urlToImage: "data:image/png;base64,AAAA" },
|
||||
],
|
||||
}),
|
||||
).toEqual([
|
||||
{ title: "Good", description: "", url: "https://abc.net.au/a", imageUrl: "https://abc.net.au/a.jpg" },
|
||||
{ title: "No image", description: "", url: "https://abc.net.au/b", imageUrl: null },
|
||||
]);
|
||||
});
|
||||
|
||||
it("returns an empty list without a payload", () => {
|
||||
expect(toNewsArticles(undefined)).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,103 @@
|
||||
export type NewsApiArticle = {
|
||||
title?: string | null;
|
||||
description?: string | null;
|
||||
url?: string | null;
|
||||
urlToImage?: string | null;
|
||||
};
|
||||
|
||||
export type NewsFeed = { url: string; xml: string };
|
||||
|
||||
export type NewsPayload = { articles: NewsApiArticle[] } | { feeds: NewsFeed[] };
|
||||
|
||||
export type NewsArticle = {
|
||||
title: string;
|
||||
description: string;
|
||||
url: string;
|
||||
imageUrl: string | null;
|
||||
};
|
||||
|
||||
function safeHttpUrl(value: string | null | undefined, base?: string): string | null {
|
||||
if (!value?.trim()) return null;
|
||||
try {
|
||||
const url = new URL(value.trim(), base);
|
||||
return url.protocol === "https:" || url.protocol === "http:" ? url.href : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function htmlToText(html: string): string {
|
||||
const doc = new DOMParser().parseFromString(html, "text/html");
|
||||
return (doc.body.textContent ?? "").replace(/\s+/g, " ").trim();
|
||||
}
|
||||
|
||||
function firstImageInHtml(html: string): string | null {
|
||||
return new DOMParser().parseFromString(html, "text/html").querySelector("img")?.getAttribute("src") ?? null;
|
||||
}
|
||||
|
||||
function children(el: Element, name: string): Element[] {
|
||||
return [...el.children].filter((child) => child.localName === name);
|
||||
}
|
||||
|
||||
function childText(el: Element, ...names: string[]): string {
|
||||
for (const name of names) {
|
||||
const text = children(el, name)[0]?.textContent?.trim();
|
||||
if (text) return text;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
function itemLink(item: Element): string {
|
||||
const links = children(item, "link");
|
||||
const alternate = links.find((link) => (link.getAttribute("rel") ?? "alternate") === "alternate");
|
||||
return alternate?.getAttribute("href") || alternate?.textContent?.trim() || childText(item, "guid", "id");
|
||||
}
|
||||
|
||||
function itemImage(item: Element, descriptionHtml: string): string | null {
|
||||
const media = [...item.getElementsByTagNameNS("*", "thumbnail"), ...item.getElementsByTagNameNS("*", "content")]
|
||||
.filter((el) => el.namespaceURI?.includes("mrss"))
|
||||
.find((el) => el.getAttribute("url") && (!el.getAttribute("medium") || el.getAttribute("medium") === "image"));
|
||||
if (media) return media.getAttribute("url");
|
||||
|
||||
const enclosure = children(item, "enclosure").find((el) => el.getAttribute("type")?.startsWith("image/"));
|
||||
if (enclosure) return enclosure.getAttribute("url");
|
||||
|
||||
return descriptionHtml ? firstImageInHtml(descriptionHtml) : null;
|
||||
}
|
||||
|
||||
export function parseFeed(xml: string, feedUrl?: string): NewsArticle[] {
|
||||
const doc = new DOMParser().parseFromString(xml, "application/xml");
|
||||
if (doc.querySelector("parsererror")) return [];
|
||||
|
||||
return [...doc.querySelectorAll("item, entry")].flatMap((item) => {
|
||||
const url = safeHttpUrl(itemLink(item), feedUrl);
|
||||
if (!url) return [];
|
||||
const descriptionHtml = childText(item, "description", "summary", "encoded", "content");
|
||||
return [
|
||||
{
|
||||
title: htmlToText(childText(item, "title")),
|
||||
description: htmlToText(descriptionHtml),
|
||||
url,
|
||||
imageUrl: safeHttpUrl(itemImage(item, descriptionHtml), url),
|
||||
},
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
export function toNewsArticles(payload: NewsPayload | undefined): NewsArticle[] {
|
||||
if (!payload) return [];
|
||||
if ("feeds" in payload) return payload.feeds.flatMap((feed) => parseFeed(feed.xml, feed.url));
|
||||
|
||||
return payload.articles.flatMap((article) => {
|
||||
const url = safeHttpUrl(article.url);
|
||||
if (!url) return [];
|
||||
return [
|
||||
{
|
||||
title: article.title ?? "",
|
||||
description: article.description ?? "",
|
||||
url,
|
||||
imageUrl: safeHttpUrl(article.urlToImage),
|
||||
},
|
||||
];
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user