refactor: remove trailing slash in site url for notification (#6660)

#### What type of PR is this?
/kind improvement
/area core
/milestone 2.20.x

#### What this PR does / why we need it:
修复 external-url 配置带了尾部斜杠导致邮件通知的查看通知链接无法访问的问题

#### Which issue(s) this PR fixes:
Fixes #6655

#### Does this PR introduce a user-facing change?
```release-note
修复 external-url 配置带了尾部斜杠导致邮件通知的查看通知链接无法访问的问题
```
pull/6671/head
guqing 2024-09-14 15:16:31 +08:00 committed by GitHub
parent a9c0ecebe3
commit 3fda9e6db4
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 32 additions and 3 deletions

View File

@ -5,7 +5,9 @@ import static org.apache.commons.lang3.StringUtils.defaultString;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
@ -40,13 +42,16 @@ public class DefaultNotificationTemplateRender implements NotificationTemplateRe
@Override
public Mono<String> render(String template, Map<String, Object> model) {
var context = new Context(Locale.getDefault(), model);
var externalUrl = Optional.ofNullable(externalUrlSupplier.getRaw())
.map(url -> StringUtils.removeEnd(url.toString(), "/"))
.orElse(StringUtils.EMPTY);
var globalAttributeMono = getBasicSetting()
.doOnNext(basic -> {
var site = new HashMap<>();
site.put("title", basic.getTitle());
site.put("logo", basic.getLogo());
site.put("subtitle", basic.getSubtitle());
site.put("url", externalUrlSupplier.getRaw());
site.put("url", externalUrl);
context.setVariable("site", site);
});
return Mono.when(globalAttributeMono)

View File

@ -9,6 +9,7 @@ import static org.mockito.Mockito.when;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.Map;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@ -88,7 +89,7 @@ class DefaultNotificationTemplateRenderTest {
Halo
http://localhost:8090
@ -101,4 +102,27 @@ class DefaultNotificationTemplateRenderTest {
eq(SystemSetting.Basic.class));
verify(externalUrlSupplier).getRaw();
}
}
@Test
void siteUrlTest() throws MalformedURLException {
when(environmentFetcher.fetch(eq(SystemSetting.Basic.GROUP), eq(SystemSetting.Basic.class)))
.thenReturn(Mono.just(new SystemSetting.Basic()));
var template = "<a th:href=\"|${site.url}/uc/notifications|\">查看通知</a>";
var expected = "<a href=\"http://localhost:8090/uc/notifications\">查看通知</a>";
when(externalUrlSupplier.getRaw()).thenReturn(new URL("http://localhost:8090/"));
templateRender.render(template,
Map.of())
.as(StepVerifier::create)
.expectNext(expected)
.verifyComplete();
when(externalUrlSupplier.getRaw()).thenReturn(new URL("http://localhost:8090"));
templateRender.render(template,
Map.of())
.as(StepVerifier::create)
.expectNext(expected)
.verifyComplete();
}
}