Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions lib/errors/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { config } from '@/config';
import { getDebugInfo, setDebugInfo } from '@/utils/debug-info';
import logger from '@/utils/logger';
import { requestMetric } from '@/utils/otel';
import { classifyFailure, reasonHeader, upstreamStatusHeader } from '@/utils/route-failure';
import Error from '@/views/error';

import NotFoundError from './types/not-found';
Expand Down Expand Up @@ -55,6 +56,8 @@ export const errorHandler: ErrorHandler = (error, ctx) => {
case 'HTTPError':
case 'RequestError':
case 'FetchError':
// The header middleware set a public max-age for the feed; a failure is not kept.
ctx.header('Cache-Control', 'no-store');
ctx.status(503);
break;
case 'RequestInProgressError':
Expand All @@ -69,9 +72,17 @@ export const errorHandler: ErrorHandler = (error, ctx) => {
errorMessage += 'The route does not exist or has been deleted.';
break;
default:
ctx.header('Cache-Control', 'no-store');
ctx.status(503);
break;
}
const failure = classifyFailure(error);
if (failure) {
ctx.header(reasonHeader, failure.reason);
if (failure.upstreamStatus) {
ctx.header(upstreamStatusHeader, String(failure.upstreamStatus));
}
}
const message = `${error.name}: ${errorMessage}`;

logger.error(`Error in ${requestPath}: ${message}`);
Expand Down
21 changes: 21 additions & 0 deletions lib/errors/types/route-failure.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
export const routeFailureReasons = ['upstream-timeout', 'upstream-status', 'upstream-unreachable', 'parse-error'] as const;

export type RouteFailureReason = (typeof routeFailureReasons)[number];

/**
* A route failed for a reason a reader of the feed can act on. The error
* handler names the reason in the `RSSHub-Error-Reason` response header.
*/
class RouteFailureError extends Error {
name = 'RouteFailureError';
reason: RouteFailureReason;
upstreamStatus?: number;

constructor(reason: RouteFailureReason, message: string, options?: { cause?: unknown; upstreamStatus?: number }) {
super(message, { cause: options?.cause });
this.reason = reason;
this.upstreamStatus = options?.upstreamStatus;
}
}

export default RouteFailureError;
137 changes: 64 additions & 73 deletions lib/routes/easylife365/changelogs.ts
Original file line number Diff line number Diff line change
@@ -1,90 +1,81 @@
import { load } from 'cheerio';

import got from '@/utils/got';

function parseDateFromLink(link: string) {
const match = link.match(/\/changelogs\/(\d{4})\/(\d{2})\/(\d{2})\//);
if (!match) {
return;
}

const [, yyyy, mm, dd] = match;
return new Date(`${yyyy}-${mm}-${dd}T00:00:00Z`).toUTCString();
import type { DataItem, Route } from '@/types';
import { parseDate } from '@/utils/parse-date';
import { fetchUpstream, requireItems } from '@/utils/route-failure';

interface ChangelogFeedItem {
content_html?: string;
date_modified?: string;
date_published?: string;
summary?: string;
tags?: string[];
title?: string;
url?: string;
}

function cleanDescription(text: string) {
return text
.replaceAll(/\s+/g, ' ')
.replace(/^←\s*Back to Changelog/, '')
.replace(/Have questions\? Reach out to us for more information\.?Contact Us$/i, '')
.trim();
}
const rootUrl = 'https://docs.easylife365.cloud';
const currentUrl = `${rootUrl}/changelogs`;
// The site's own feed of its newest changelogs, with each one's full text.
const feedUrl = `${currentUrl}/feed.json`;

const productNames: Record<string, string> = {
collab: 'Collaboration',
identity: 'Identity',
mail: 'Mail',
meet: 'Meet',
tipster: 'Tipster',
};

function getProductFromLink(link: string) {
const match = link.match(/\/changelogs\/\d{4}\/\d{2}\/\d{2}\/([^/]+)\//);
if (!match) {
return '';
}
const product = link.match(/\/changelogs\/\d{4}\/\d{2}\/\d{2}\/([^/]+)\//)?.[1];

const productMap: Record<string, string> = {
collab: 'Collaboration',
identity: 'Identity',
mail: 'Mail',
meet: 'Meet',
tipster: 'Tipster',
};
return product ? (productNames[product] ?? product) : '';
}

function getDateFromLink(link: string) {
const match = link.match(/\/changelogs\/(\d{4})\/(\d{2})\/(\d{2})\//);

return productMap[match[1]] ?? match[1];
return match ? parseDate(`${match[1]}-${match[2]}-${match[3]}`) : undefined;
}

export const route = {
export const route: Route = {
path: '/changelogs',
name: 'Changelogs',
categories: ['program-update'],
example: '/easylife365/changelogs',
maintainers: ['dein-github-name'],
handler: async () => {
const rootUrl = 'https://docs.easylife365.cloud';
const currentUrl = `${rootUrl}/changelogs`;

const response = await got(currentUrl);
const $ = load(response.data);

const links = [
...new Set(
$('a[href*="/changelogs/"]')
.toArray()
.map((el) => $(el).attr('href'))
.filter((href): href is string => typeof href === 'string' && href.length > 0)
.map((href) => new URL(href, rootUrl).toString())
),
];

const item = await Promise.all(
links.map(async (link) => {
const detailResponse = await got(link);
const detail$ = load(detailResponse.data);

const rawTitle = detail$('main h1').first().text().trim() || detail$('h1').first().text().trim() || detail$('title').first().text().trim() || link.split('/').at(-1) || 'Untitled';

const product = getProductFromLink(link);
const title = product ? `${product}: ${rawTitle}` : rawTitle;
maintainers: [],
radar: [
{
source: ['docs.easylife365.cloud/changelogs'],
target: '/changelogs',
},
],
handler,
url: 'docs.easylife365.cloud/changelogs',
};

const rawDescription = detail$('main').first().text() || detail$('article').first().text() || '';
async function handler() {
const feed = await fetchUpstream<{ items?: ChangelogFeedItem[] }>(feedUrl, { responseType: 'json' });
const entries = Array.isArray(feed?.items) ? feed.items.filter((entry) => typeof entry?.url === 'string' && entry.url.length > 0) : [];

return {
title,
link,
description: cleanDescription(rawDescription),
pubDate: parseDateFromLink(link),
};
})
);
const item = requireItems(entries, 'changelog entries').map((entry): DataItem => {
const link = new URL(entry.url!, rootUrl).toString();
const product = getProductFromLink(link);
const rawTitle = entry.title || link.split('/').at(-1) || 'Untitled';
const date = entry.date_published || entry.date_modified;

return {
title: 'EasyLife 365 Changelogs',
link: currentUrl,
item,
title: product ? `${product}: ${rawTitle}` : rawTitle,
link,
description: entry.content_html || entry.summary || '',
pubDate: date ? parseDate(date) : getDateFromLink(link),
category: entry.tags?.length ? entry.tags : undefined,
};
},
};
});

return {
title: 'EasyLife 365 Changelogs',
link: currentUrl,
item,
language: 'en' as const,
};
}
7 changes: 4 additions & 3 deletions lib/routes/flexopus/changelog.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { load } from 'cheerio';

import type { Route } from '@/types';
import ofetch from '@/utils/ofetch';
import { parseDate } from '@/utils/parse-date';
import { fetchUpstream, requireItems } from '@/utils/route-failure';

const baseUrl = 'https://help.flexopus.com';
const apiKey = 'c1841f6cc3813bc6405fcf7353';
Expand Down Expand Up @@ -33,15 +33,16 @@ export const route: Route = {
};

async function handler() {
const data = await ofetch(`${baseUrl}/en/ghost/api/content/posts/`, {
const data = await fetchUpstream<{ posts?: Array<Record<string, string>> }>(`${baseUrl}/en/ghost/api/content/posts/`, {
query: {
key: apiKey,
filter: 'tag:hash-changelog',
limit: 15,
},
responseType: 'json',
});

const items = data.posts.map((post) => {
const items = requireItems(Array.isArray(data?.posts) ? data.posts : [], 'changelog posts').map((post) => {
const $ = load(post.html || '');
$('[referrerpolicy]').removeAttr('referrerpolicy');
$('.kg-callout-card-accent').remove();
Expand Down
13 changes: 8 additions & 5 deletions lib/routes/microsoft/message-center.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { load } from 'cheerio';

import RouteFailureError from '@/errors/types/route-failure';
import type { DataItem, Route } from '@/types';
import { ViewType } from '@/types';
import got from '@/utils/got';
import { parseDate } from '@/utils/parse-date';
import { fetchUpstream, requireItems } from '@/utils/route-failure';

interface MessageCenterDetail {
Name: string;
Expand Down Expand Up @@ -71,14 +72,16 @@ export const route: Route = {
async function handler(ctx) {
const limit = Number.parseInt(ctx.req.query('limit') ?? String(defaultLimit), 10);
const pageSize = Number.isNaN(limit) || limit <= 0 ? defaultLimit : limit;
const { data: messages }: { data: MessageCenterMessage[] } = await got(dataUrl);
const messages = await fetchUpstream<MessageCenterMessage[]>(dataUrl, { responseType: 'json' });

if (!Array.isArray(messages)) {
throw new TypeError('Failed to fetch Microsoft 365 Message Center archive data.');
throw new RouteFailureError('parse-error', 'The Microsoft 365 Message Center archive is not a list of messages.');
}

const item = messages
.filter((message) => isMessageCenterMessage(message))
const item = requireItems(
messages.filter((message) => isMessageCenterMessage(message)),
'Message Center posts'
)
.toSorted((a, b) => getTimestamp(b) - getTimestamp(a))
.slice(0, pageSize)
.map((message): DataItem => {
Expand Down
8 changes: 4 additions & 4 deletions lib/routes/microsoftlearn/entra-whats-new.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { load } from 'cheerio';

import got from '@/utils/got';
import { parseDate } from '@/utils/parse-date';
import { fetchUpstream, requireItems } from '@/utils/route-failure';

export const route = {
path: '/entra/whats-new',
Expand All @@ -12,8 +12,8 @@ export const route = {
handler: async () => {
const currentUrl = 'https://learn.microsoft.com/en-us/entra/fundamentals/whats-new';

const response = await got(currentUrl);
const $ = load(response.data);
const page = await fetchUpstream(currentUrl);
const $ = load(page);

const item: Array<{
title: string;
Expand Down Expand Up @@ -75,7 +75,7 @@ export const route = {
return {
title: 'Microsoft Entra releases and announcements',
link: currentUrl,
item,
item: requireItems(item, 'announcements'),
};
},
};
12 changes: 10 additions & 2 deletions lib/routes/microsoftlearn/intune-blog.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import RouteFailureError from '@/errors/types/route-failure';
import type { Data, DataItem, Route } from '@/types';
import { parseDate } from '@/utils/parse-date';
import { fetchUpstream, requireItems } from '@/utils/route-failure';
import parser from '@/utils/rss-parser';

export const route: Route = {
Expand All @@ -20,9 +22,15 @@ export const route: Route = {
async function handler(): Promise<Data> {
const feedUrl = 'https://techcommunity.microsoft.com/t5/s/gxcuf89792/rss/board?board.id=microsoftintuneblog';

const feed = await parser.parseURL(feedUrl);
const document = await fetchUpstream(feedUrl);
let feed: Awaited<ReturnType<typeof parser.parseString>>;
try {
feed = await parser.parseString(document);
} catch (error) {
throw new RouteFailureError('parse-error', 'The Intune blog did not answer with a feed.', { cause: error });
}

const items: DataItem[] = feed.items.map((item) => ({
const items: DataItem[] = requireItems(feed.items ?? [], 'blog posts').map((item) => ({
title: item.title ?? '',
link: item.link,
description: item.content ?? item.contentSnippet ?? '',
Expand Down
8 changes: 4 additions & 4 deletions lib/routes/microsoftlearn/intune-in-development.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { load } from 'cheerio';

import type { Route } from '@/types';
import got from '@/utils/got';
import { fetchUpstream, requireItems } from '@/utils/route-failure';

export const route: Route = {
path: '/intune/in-development',
Expand All @@ -12,8 +12,8 @@ export const route: Route = {
handler: async () => {
const currentUrl = 'https://learn.microsoft.com/en-us/intune/whats-new/in-development';

const response = await got(currentUrl);
const $ = load(response.data);
const page = await fetchUpstream(currentUrl);
const $ = load(page);

const items: Array<{ title: string; link: string; description: string }> = [];

Expand Down Expand Up @@ -65,7 +65,7 @@ export const route: Route = {
return {
title: 'In development for Microsoft Intune',
link: currentUrl,
item: items,
item: requireItems(items, 'features in development'),
};
},
};
8 changes: 4 additions & 4 deletions lib/routes/microsoftlearn/intune-whats-new.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { load } from 'cheerio';

import type { Route } from '@/types';
import got from '@/utils/got';
import { parseDate } from '@/utils/parse-date';
import { fetchUpstream, requireItems } from '@/utils/route-failure';

export const route: Route = {
path: '/intune/whats-new',
Expand All @@ -13,8 +13,8 @@ export const route: Route = {
handler: async () => {
const currentUrl = 'https://learn.microsoft.com/en-us/intune/whats-new/';

const response = await got(currentUrl);
const $ = load(response.data);
const page = await fetchUpstream(currentUrl);
const $ = load(page);

const item: Array<{ title: string; link: string; description: string; pubDate?: Date }> = [];

Expand Down Expand Up @@ -82,7 +82,7 @@ export const route: Route = {
return {
title: "What's new in Microsoft Intune",
link: currentUrl,
item,
item: requireItems(item, 'features'),
};
},
};
Loading
Loading