generated from mantinedev/next-pages-template
-
-
Notifications
You must be signed in to change notification settings - Fork 255
/
rss.ts
220 lines (199 loc) · 5.46 KB
/
rss.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
import { TRPCError } from '@trpc/server';
import Consola from 'consola';
import { decode, encode } from 'html-entities';
import RssParser from 'rss-parser';
import xss from 'xss';
import { z } from 'zod';
import { getConfig } from '~/tools/config/getConfig';
import { Stopwatch } from '~/tools/shared/time/stopwatch.tool';
import { IRssWidget } from '~/widgets/rss/RssWidgetTile';
import { createTRPCRouter, publicProcedure } from '../trpc';
type CustomItem = {
'media:content': string;
enclosure: {
url: string;
};
'media:group'?: {
'media:description'?: string;
'media:thumbnail'?: string;
};
pubDate?: string;
};
const rssFeedResultObjectSchema = z
.object({
success: z.literal(false),
feed: z.undefined(),
})
.or(
z.object({
success: z.literal(true),
feed: z.object({
title: z.string().or(z.undefined()),
items: z.array(
z.object({
link: z.string(),
enclosure: z
.object({
url: z.string(),
})
.or(z.undefined()),
categories: z.array(z.string()).or(z.undefined()),
title: z.string(),
content: z.string(),
pubDate: z.date().optional(),
})
),
}),
})
);
export const rssRouter = createTRPCRouter({
all: publicProcedure
.input(
z.object({
widgetId: z.string().uuid(),
feedUrls: z.array(z.string()),
configName: z.string(),
})
)
.output(z.array(rssFeedResultObjectSchema))
.query(async ({ input }) => {
const config = getConfig(input.configName);
const rssWidget = config.widgets.find((x) => x.type === 'rss' && x.id === input.widgetId) as
| IRssWidget
| undefined;
if (!rssWidget) {
throw new TRPCError({
code: 'NOT_FOUND',
message: 'required widget does not exist',
});
}
if (input.feedUrls.length === 0) {
return [];
}
return await Promise.all(
input.feedUrls.map(async (feedUrl) =>
getFeedUrl(
feedUrl,
rssWidget.properties.dangerousAllowSanitizedItemContent,
rssWidget.properties.sortPostsWithoutPublishDateToTheTop,
rssWidget.properties.maximumAmountOfPosts
)
)
);
}),
});
const getFeedUrl = async (
feedUrl: string,
dangerousAllowSanitizedItemContent: boolean,
sortPostsWithoutPubDateToTop: boolean,
maximumAmountOfPosts: number
) => {
Consola.info(`Requesting RSS feed at url ${feedUrl}`);
const stopWatch = new Stopwatch();
const feed = await parser.parseURL(feedUrl);
Consola.info(`Retrieved RSS feed after ${stopWatch.getEllapsedMilliseconds()} milliseconds`);
const orderedFeed = {
...feed,
items: feed.items
.map(
(item: {
title: string;
content: string;
'content:encoded': string;
'media:group'?: {
'media:description'?: string;
'media:thumbnail'?: string;
};
categories: string[] | { _: string }[];
pubDate?: string;
}) => {
return {
...item,
categories: item.categories
?.map((category) => (typeof category === 'string' ? category : category._))
.filter((category: unknown): category is string => typeof category === 'string'),
title: item.title ? decode(item.title) : undefined,
content: processItemContent(
item['content:encoded'] ?? item.content ?? item['media:group']?.['media:description'],
dangerousAllowSanitizedItemContent
),
enclosure: createEnclosure(item),
link: createLink(item),
pubDate: item.pubDate ? new Date(item.pubDate) : null,
};
}
)
.sort((post1: { pubDate: number }, post2: { pubDate: number }) => {
if (!post1.pubDate || !post2.pubDate) {
return sortPostsWithoutPubDateToTop ? 1 : 0;
}
return post1.pubDate - post2.pubDate;
}),
};
return {
feed: orderedFeed,
success: orderedFeed?.items !== undefined,
};
};
const processItemContent = (content: string, dangerousAllowSanitizedItemContent: boolean) => {
if (dangerousAllowSanitizedItemContent) {
return xss(content, {
allowList: {
p: [],
h1: [],
h2: [],
h3: [],
h4: [],
h5: [],
h6: [],
a: ['href'],
b: [],
strong: [],
i: [],
em: [],
img: ['src', 'width', 'height', 'alt'],
br: [],
small: [],
ul: [],
li: [],
ol: [],
figure: [],
svg: [],
code: [],
mark: [],
blockquote: [],
},
});
}
return encode(content, {
level: 'html5',
});
};
const createLink = (item: any) => {
if (item.link) {
return item.link;
}
return item.guid;
};
const createEnclosure = (item: any) => {
if (item.enclosure) {
return item.enclosure;
}
if (item['media:content']) {
return {
url: item['media:content'].$.url,
};
}
if (item['media:group'] && item['media:group']['media:thumbnail']) {
// no clue why this janky parse is needed
return {
url: item['media:group']['media:thumbnail'][0].$.url,
};
}
return undefined;
};
const parser: RssParser<any, CustomItem> = new RssParser({
customFields: {
item: ['media:content', 'enclosure', 'media:group'],
},
});