-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathRssXmlBuilder.java
More file actions
354 lines (312 loc) · 13.5 KB
/
RssXmlBuilder.java
File metadata and controls
354 lines (312 loc) · 13.5 KB
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
package run.halo.feed;
import com.google.common.base.Throwables;
import java.io.StringReader;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Optional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
import org.springframework.util.CollectionUtils;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClientException;
import org.springframework.web.util.UriComponentsBuilder;
import org.springframework.web.util.UriUtils;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.netty.http.client.HttpClient;
import run.halo.feed.telemetry.TelemetryEndpoint;
@Slf4j
public class RssXmlBuilder {
static final String UA =
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) "
+ "Chrome/131.0.0.0 Safari/537.36";
private final WebClient webClient = WebClient.builder()
.clientConnector(new ReactorClientHttpConnector(HttpClient.create()
.responseTimeout(Duration.ofSeconds(1))
.followRedirect(true))
)
.build();
private RSS2 rss2;
private String generator = "Halo v2.0";
private String extractRssTags;
private Instant lastBuildDate = Instant.now();
private String requestPath;
private String externalUrl;
public RssXmlBuilder withRss2(RSS2 rss2) {
this.rss2 = rss2;
return this;
}
public RssXmlBuilder withRequestPath(String requestPath) {
this.requestPath = requestPath;
return this;
}
/**
* For test.
*/
RssXmlBuilder withGenerator(String generator) {
this.generator = generator;
return this;
}
public RssXmlBuilder withExtractRssTags(String extractRssTags) {
this.extractRssTags = extractRssTags;
return this;
}
/**
* For test.
*/
RssXmlBuilder withLastBuildDate(Instant lastBuildDate) {
this.lastBuildDate = lastBuildDate;
return this;
}
RssXmlBuilder withExternalUrl(String externalUrl) {
this.externalUrl = externalUrl;
return this;
}
public Mono<String> toXmlString() {
Document document = DocumentHelper.createDocument();
Element root = DocumentHelper.createElement("rss");
root.addAttribute("version", "2.0");
root.addNamespace("dc", "http://purl.org/dc/elements/1.1/");
root.addNamespace("atom", "http://www.w3.org/2005/Atom");
root.addNamespace("media", "http://search.yahoo.com/mrss/");
document.setRootElement(root);
Element channel = root.addElement("channel");
channel.addElement("title").addText(rss2.getTitle());
channel.addElement("link").addText(rss2.getLink());
if (StringUtils.isNotBlank(requestPath)) {
channel.addElement("atom:link")
.addAttribute("href", UriComponentsBuilder.fromUriString(rss2.getLink())
.path(requestPath).toUriString()
)
.addAttribute("rel", "self")
.addAttribute("type", "application/rss+xml");
}
var description = StringUtils.defaultIfBlank(rss2.getDescription(), rss2.getTitle());
var secureDescription = XmlCharUtils.removeInvalidXmlChar(description);
channel.addElement("description").addText(secureDescription);
channel.addElement("generator").addText(generator);
channel.addElement("language")
.addText(StringUtils.defaultIfBlank(rss2.getLanguage(), "zh-cn"));
if (StringUtils.isNotBlank(rss2.getImage())) {
Element imageElement = channel.addElement("image");
imageElement.addElement("url").addText(rss2.getImage());
imageElement.addElement("title").addText(rss2.getTitle());
imageElement.addElement("link").addText(rss2.getLink());
}
channel.addElement("lastBuildDate")
.addText(instantToString(lastBuildDate));
if (StringUtils.isNotBlank(extractRssTags)) {
try {
var extractRssTagsElement = parseXmlString(extractRssTags);
for (Element element : extractRssTagsElement.elements()) {
Element newElement = channel.addElement(element.getName());
copyAttributesAndChildren(newElement, element);
}
} catch (Throwable e) {
// ignore
log.error("无法注入自定义的 RSS 标签, 确保是正确的 XML 格式",
Throwables.getRootCause(e));
}
}
var items = rss2.getItems();
return createItemElementsToChannel(channel, items)
.thenReturn(document)
.map(Document::asXML);
}
private void copyAttributesAndChildren(Element target, Element source) {
for (var attribute : source.attributes()) {
target.addAttribute(attribute.getName(), attribute.getValue());
}
if (source.getTextTrim() != null) {
target.setText(source.getTextTrim());
}
for (Element child : source.elements()) {
Element newChild = target.addElement(child.getName());
copyAttributesAndChildren(newChild, child);
}
}
private Element parseXmlString(String xml) throws DocumentException {
// for SAXReader to load class from current classloader
var originalContextClassloader = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
try {
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader("""
<root>
%s
</root>
""".formatted(xml)));
return document.getRootElement();
} finally {
Thread.currentThread().setContextClassLoader(originalContextClassloader);
}
}
private Mono<Void> createItemElementsToChannel(Element channel, List<RSS2.Item> items) {
if (CollectionUtils.isEmpty(items)) {
return Mono.empty();
}
return Flux.fromIterable(items)
.flatMap(item -> createItemElementToChannel(channel, item))
.then();
}
private Mono<Void> createItemElementToChannel(Element channel, RSS2.Item item) {
Element itemElement = channel.addElement("item");
itemElement.addElement("title")
.addCDATA(XmlCharUtils.removeInvalidXmlChar(item.getTitle()));
itemElement.addElement("link").addText(item.getLink());
var description = Optional.of(getDescriptionWithTelemetry(item))
.map(content -> {
if (externalUrl != null) {
return new RelativeLinkProcessor(externalUrl)
.processForHtml(content);
}
return content;
})
.map(XmlCharUtils::removeInvalidXmlChar)
.orElseThrow();
itemElement.addElement("description").addCDATA(description);
itemElement.addElement("guid")
.addAttribute("isPermaLink", "false")
.addText(item.getGuid());
if (StringUtils.isNotBlank(item.getAuthor())) {
// https://www.rssboard.org/rss-validator/docs/error/InvalidContact.html
itemElement.addElement("dc:creator")
.addText(item.getAuthor());
}
Mono<Void> handleEnclosure = Mono.empty();
if (StringUtils.isNotBlank(item.getEnclosureUrl())) {
var enclosureElement = itemElement.addElement("enclosure")
.addAttribute("url", item.getEnclosureUrl())
.addAttribute("type", item.getEnclosureType());
var enclosureLength = item.getEnclosureLength();
enclosureElement.addAttribute("length", enclosureLength);
if (StringUtils.isBlank(enclosureLength)) {
// https://www.rssboard.org/rss-validator/docs/error/MissingAttribute.html
handleEnclosure = getFileSizeBytes(item.getEnclosureUrl())
.doOnNext(fileBytes -> enclosureElement.addAttribute("length", String.valueOf(fileBytes)))
.then();
}
}
nullSafeList(item.getCategories())
.forEach(category -> itemElement.addElement("category").addText(category));
itemElement.addElement("pubDate")
.addText(instantToString(item.getPubDate()));
// support for media:content
nullSafeList(item.getMediaContents()).forEach(mediaContent -> {
Element mediaElement = itemElement.addElement("media:content")
.addAttribute("url", mediaContent.getUrl())
.addAttribute("type", mediaContent.getType());
if (mediaContent.getMediaType() != null) {
mediaElement.addAttribute("medium",
mediaContent.getMediaType().name().toLowerCase());
}
if (StringUtils.isNotBlank(mediaContent.getFileSize())) {
mediaElement.addAttribute("fileSize", mediaContent.getFileSize());
}
if (StringUtils.isNotBlank(mediaContent.getDuration())) {
mediaElement.addAttribute("duration", mediaContent.getDuration());
}
if (StringUtils.isNotBlank(mediaContent.getHeight())) {
mediaElement.addAttribute("height", mediaContent.getHeight());
}
if (StringUtils.isNotBlank(mediaContent.getWidth())) {
mediaElement.addAttribute("width", mediaContent.getWidth());
}
// add nested media:thumbnail
var thumbnail = mediaContent.getThumbnail();
if (thumbnail != null) {
Element thumbnailElement = mediaElement.addElement("media:thumbnail")
.addAttribute("url", thumbnail.getUrl());
if (StringUtils.isNotBlank(thumbnail.getHeight())) {
thumbnailElement.addAttribute("height", thumbnail.getHeight());
}
if (StringUtils.isNotBlank(thumbnail.getWidth())) {
thumbnailElement.addAttribute("width", thumbnail.getWidth());
}
}
});
return handleEnclosure;
}
private String getDescriptionWithTelemetry(RSS2.Item item) {
if (StringUtils.isBlank(externalUrl)) {
return item.getDescription();
}
var uri = UriComponentsBuilder.fromUriString(item.getLink())
.build();
var telemetryBaseUri = externalUrl + TelemetryEndpoint.TELEMETRY_PATH;
var telemetryUri = UriComponentsBuilder.fromUriString(telemetryBaseUri)
.queryParam("title", UriUtils.encode(item.getTitle(), StandardCharsets.UTF_8))
.queryParam("url", uri.getPath())
.build(true)
.toUriString();
// Build the telemetry image HTML
var telemetryImageHtml = String.format(
"<img src=\"%s\" width=\"1\" height=\"1\" alt=\"\" style=\"opacity:0;\" />",
telemetryUri
);
// Append telemetry image to description
return telemetryImageHtml + item.getDescription();
}
static <T> List<T> nullSafeList(List<T> list) {
return list == null ? List.of() : list;
}
static String instantToString(Instant instant) {
return instant.atOffset(ZoneOffset.UTC)
.format(DateTimeFormatter.RFC_1123_DATE_TIME);
}
@NonNull
Mono<Long> getFileSizeBytes(String url) {
return webClient.get()
.uri(URI.create(url))
.header(HttpHeaders.USER_AGENT, UA)
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Range
.header(HttpHeaders.RANGE, "bytes=0-0")
.headers(headers -> {
if (StringUtils.isNotBlank(externalUrl)) {
// For Referrer anti-hotlinking
headers.set(HttpHeaders.REFERER, externalUrl);
}
})
.retrieve()
.toBodilessEntity()
.map(HttpEntity::getHeaders)
.mapNotNull(headers -> headers.getFirst(HttpHeaders.CONTENT_RANGE))
.mapNotNull(RssXmlBuilder::parseLengthOfContentRange)
.doOnError(e -> log.debug("Failed to get file size from url: {}", url,
Throwables.getRootCause(e))
)
.onErrorReturn(0L)
.defaultIfEmpty(0L);
}
@Nullable
static Long parseLengthOfContentRange(@Nullable String contentRange) {
if (contentRange == null) {
return null;
}
// Refer to https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range#syntax
var range = contentRange.split("/");
if (range.length != 2) {
return null;
}
var lengthStr = range[1];
if ("*".equals(lengthStr)) {
return null;
}
return Long.parseLong(range[1]);
}
}