feat: 操作审计支持按筛选条件导出 CSV
- 后端新增导出端点 GET /apis/audit.guichumo.com/v1alpha1/auditlogs/-/export: 筛选参数与 query 完全一致(条件构造抽取为 AuditLogFilters 共用), 按时间升序分批(每批 200)遍历全量、流式输出 UTF-8 BOM CSV(Excel/WPS 直开), 字段引号转义 + 公式注入防护;列含 describeOperation 移植版中文操作描述(OperationDescription) - role-template 追加 auditlogs/export(动词仍 get/list,保持只读语义) - Console 列表页工具栏新增「导出」按钮:按当前筛选条件 fetch → blob → a[download] 下载 - 测试:后端新增导出端点/分批取数/CSV 转义/操作描述用例(71 个全绿), 前端新增导出链路结构性回归 spec(31 个全绿)+ vue-tsc 通过 - 文档:设计文档 V2 规划项标注已实现,README 补导出说明
This commit is contained in:
+143
@@ -0,0 +1,143 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.List;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.core.io.buffer.DataBuffer;
|
||||
import org.springframework.core.io.buffer.DataBufferFactory;
|
||||
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.reactive.function.server.ServerResponse;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import run.halo.app.extension.ListOptions;
|
||||
import run.halo.app.extension.PageRequestImpl;
|
||||
import run.halo.app.extension.ReactiveExtensionClient;
|
||||
|
||||
/**
|
||||
* 审计日志 CSV 导出(按筛选条件导出,设计文档 V2 规划项)。
|
||||
*
|
||||
* <p>按时间升序分批遍历(每批 {@value #EXPORT_BATCH_SIZE} 条,循环至不足一批,
|
||||
* 与 {@code RetentionCleaner} 的分批模式一致)拉取筛选命中的全部记录,
|
||||
* 流式拼接 CSV 行输出,内存仅保留当前批。升序的原因:新记录时间戳更大、
|
||||
* 总是排在末尾,导出期间并发写入不会打乱分页边界。
|
||||
*
|
||||
* <p>CSV 采用 UTF-8 BOM + \r\n 行结束符,Excel/WPS 双击打开中文不乱码;
|
||||
* 字段做引号转义与公式注入防护(见 {@link #escape})。
|
||||
*/
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class AuditLogCsvExporter {
|
||||
|
||||
/** 每批查询条数。 */
|
||||
static final int EXPORT_BATCH_SIZE = 200;
|
||||
|
||||
/** CSV 列题头(与 UI 列表列对应)。 */
|
||||
private static final String CSV_HEADER =
|
||||
"操作时间,操作者,动作,资源类型,资源名称,路径,操作描述,结果,状态码,来源IP,User-Agent";
|
||||
|
||||
private static final DataBufferFactory BUFFER_FACTORY =
|
||||
DefaultDataBufferFactory.sharedInstance;
|
||||
|
||||
/** 操作时间列格式(服务器时区,与 UI 列表展示格式一致)。 */
|
||||
private static final DateTimeFormatter TIME_FORMATTER =
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.systemDefault());
|
||||
|
||||
/** 导出文件名中的时间戳(不能含冒号/空格等文件名非法字符)。 */
|
||||
private static final DateTimeFormatter FILENAME_TIME_FORMATTER =
|
||||
DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss").withZone(ZoneId.systemDefault());
|
||||
|
||||
private final ReactiveExtensionClient client;
|
||||
|
||||
/** 导出为 CSV 附件下载响应(流式输出)。 */
|
||||
public Mono<ServerResponse> exportResponse(ListOptions options) {
|
||||
var filename = "audit-logs-" + FILENAME_TIME_FORMATTER.format(Instant.now()) + ".csv";
|
||||
return ServerResponse.ok()
|
||||
.contentType(MediaType.parseMediaType("text/csv;charset=UTF-8"))
|
||||
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + filename)
|
||||
.body(csvLines(options)
|
||||
.map(line -> BUFFER_FACTORY.wrap(line.getBytes(StandardCharsets.UTF_8))),
|
||||
DataBuffer.class);
|
||||
}
|
||||
|
||||
private Flux<String> csvLines(ListOptions options) {
|
||||
// 首行带 UTF-8 BOM;每行统一以 \r\n 结束(Excel/WPS 友好)
|
||||
return Flux.concat(
|
||||
Flux.just("\uFEFF" + CSV_HEADER),
|
||||
fetchAll(options).map(this::toCsvLine))
|
||||
.map(line -> line + "\r\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* 按时间升序分批遍历筛选命中的全部记录:每批 {@value #EXPORT_BATCH_SIZE} 条,
|
||||
* 不足一批说明已取完(满一批时可能恰好取尽,多做一次空页查询,无害)。
|
||||
*/
|
||||
Flux<AuditLog> fetchAll(ListOptions options) {
|
||||
return fetchBatch(options, 1);
|
||||
}
|
||||
|
||||
private Flux<AuditLog> fetchBatch(ListOptions options, int page) {
|
||||
var pageable = PageRequestImpl.of(page, EXPORT_BATCH_SIZE,
|
||||
Sort.by(Sort.Order.asc("metadata.creationTimestamp")));
|
||||
return client.listBy(AuditLog.class, options, pageable)
|
||||
.flatMapMany(result -> {
|
||||
var items = result.getItems() != null
|
||||
? result.getItems()
|
||||
: List.<AuditLog>of();
|
||||
if (items.size() < EXPORT_BATCH_SIZE) {
|
||||
return Flux.fromIterable(items);
|
||||
}
|
||||
return Flux.fromIterable(items).concatWith(fetchBatch(options, page + 1));
|
||||
});
|
||||
}
|
||||
|
||||
private String toCsvLine(AuditLog log) {
|
||||
var spec = log.getSpec();
|
||||
var statusCode = spec.getStatusCode();
|
||||
// 结果语义与前端 isSuccessful 一致:2xx/3xx 成功,其余(含空)失败
|
||||
var success = statusCode != null && statusCode >= 200 && statusCode < 400;
|
||||
return String.join(",",
|
||||
escape(formatTime(log.getMetadata().getCreationTimestamp())),
|
||||
escape(spec.getUsername()),
|
||||
escape(spec.getMethod()),
|
||||
escape(spec.getResourceType()),
|
||||
escape(spec.getResourceName()),
|
||||
escape(spec.getPath()),
|
||||
escape(OperationDescription.describe(
|
||||
spec.getMethod(), spec.getResourceType(), spec.getPath())),
|
||||
escape(success ? "成功" : "失败"),
|
||||
escape(statusCode == null ? null : String.valueOf(statusCode)),
|
||||
escape(spec.getRemoteIp()),
|
||||
escape(spec.getUserAgent()));
|
||||
}
|
||||
|
||||
private static String formatTime(Instant instant) {
|
||||
return instant == null ? "" : TIME_FORMATTER.format(instant);
|
||||
}
|
||||
|
||||
/**
|
||||
* CSV 字段转义:含逗号/引号/换行的字段加引号、内部引号翻倍;
|
||||
* 以 =、+、-、@、Tab、CR 开头的字段加单引号前缀(公式注入防护,Excel/WPS 显示时忽略)。
|
||||
*/
|
||||
static String escape(String value) {
|
||||
if (value == null || value.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
var first = value.charAt(0);
|
||||
var safe = first == '=' || first == '+' || first == '-' || first == '@'
|
||||
|| first == '\t' || first == '\r'
|
||||
? "'" + value
|
||||
: value;
|
||||
if (safe.indexOf(',') >= 0 || safe.indexOf('"') >= 0
|
||||
|| safe.indexOf('\n') >= 0 || safe.indexOf('\r') >= 0) {
|
||||
return '"' + safe.replace("\"", "\"\"") + '"';
|
||||
}
|
||||
return safe;
|
||||
}
|
||||
}
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import org.springframework.util.MultiValueMap;
|
||||
import org.springframework.util.StringUtils;
|
||||
import run.halo.app.extension.ListOptions;
|
||||
import run.halo.app.extension.router.selector.FieldSelector;
|
||||
import run.halo.app.extension.index.query.Condition;
|
||||
import run.halo.app.extension.index.query.Queries;
|
||||
|
||||
/**
|
||||
* 审计日志查询/导出共用的筛选条件构造(技术方案 5.3):
|
||||
* fieldSelector 等值筛选、关键字、结果、时间区间 → {@link ListOptions}。
|
||||
*
|
||||
* <p>由查询端点与导出端点共用,非法参数抛 {@link IllegalArgumentException},
|
||||
* 由端点层统一转 400(错误消息与拆分前保持一致)。
|
||||
*/
|
||||
final class AuditLogFilters {
|
||||
|
||||
/** fieldSelector 支持等值筛选的字段白名单(与已注册索引一一对应)。 */
|
||||
static final Set<String> FILTERABLE_FIELDS =
|
||||
Set.of("spec.username", "spec.resourceType", "spec.method", "spec.statusCode");
|
||||
|
||||
private AuditLogFilters() {
|
||||
}
|
||||
|
||||
/** 从查询参数构造筛选条件,非法参数抛 {@link IllegalArgumentException}。 */
|
||||
static ListOptions fromQueryParams(MultiValueMap<String, String> params) {
|
||||
var conditions = new ArrayList<Condition>();
|
||||
|
||||
// fieldSelector 等值筛选:field=value(多个 fieldSelector 参数叠加 AND)
|
||||
for (var term : params.getOrDefault("fieldSelector", List.of())) {
|
||||
var idx = term.indexOf('=');
|
||||
if (idx <= 0) {
|
||||
throw new IllegalArgumentException(
|
||||
"Invalid fieldSelector term, expect field=value: " + term);
|
||||
}
|
||||
var field = term.substring(0, idx).trim();
|
||||
var value = term.substring(idx + 1).trim();
|
||||
if (!FILTERABLE_FIELDS.contains(field)) {
|
||||
throw new IllegalArgumentException("Field not filterable: " + field);
|
||||
}
|
||||
conditions.add(Queries.equal(field, value));
|
||||
}
|
||||
|
||||
// 关键字:资源名称 / 完整路径 模糊匹配(OR)
|
||||
var keyword = params.getFirst("keyword");
|
||||
if (StringUtils.hasText(keyword)) {
|
||||
var kw = keyword.trim();
|
||||
conditions.add(Queries.or(
|
||||
Queries.contains("spec.resourceName", kw),
|
||||
Queries.contains("spec.path", kw)));
|
||||
}
|
||||
|
||||
// 结果筛选:success = 2xx/3xx,failure = 4xx/5xx
|
||||
var resultFilter = params.getFirst("result");
|
||||
if (StringUtils.hasText(resultFilter)) {
|
||||
switch (resultFilter.trim().toLowerCase()) {
|
||||
case "success" -> {
|
||||
conditions.add(Queries.greaterThan("spec.statusCode", "200", true));
|
||||
conditions.add(Queries.lessThan("spec.statusCode", "400", true));
|
||||
}
|
||||
case "failure" -> conditions.add(
|
||||
Queries.greaterThan("spec.statusCode", "400", true));
|
||||
default -> throw new IllegalArgumentException(
|
||||
"Invalid result, expect success or failure: " + resultFilter);
|
||||
}
|
||||
}
|
||||
|
||||
// 时间区间(含边界,ISO-8601 Instant)
|
||||
try {
|
||||
var start = parseInstant(params.getFirst("startTime"));
|
||||
var end = parseInstant(params.getFirst("endTime"));
|
||||
if (start != null) {
|
||||
conditions.add(Queries.greaterThan("metadata.creationTimestamp",
|
||||
start.toString(), true));
|
||||
}
|
||||
if (end != null) {
|
||||
conditions.add(Queries.lessThan("metadata.creationTimestamp",
|
||||
end.toString(), true));
|
||||
}
|
||||
} catch (DateTimeParseException e) {
|
||||
throw new IllegalArgumentException(
|
||||
"Invalid time format, expect ISO-8601 instant: " + e.getMessage());
|
||||
}
|
||||
|
||||
return conditions.isEmpty()
|
||||
? new ListOptions().setFieldSelector(FieldSelector.all())
|
||||
: new ListOptions().setFieldSelector(
|
||||
FieldSelector.of(conditions.size() == 1 ? conditions.get(0)
|
||||
: Queries.and(conditions.get(0),
|
||||
conditions.subList(1, conditions.size())
|
||||
.toArray(Condition[]::new))));
|
||||
}
|
||||
|
||||
private static Instant parseInstant(String value) {
|
||||
if (!StringUtils.hasText(value)) {
|
||||
return null;
|
||||
}
|
||||
return Instant.parse(value.trim());
|
||||
}
|
||||
}
|
||||
+26
-82
@@ -1,10 +1,6 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.data.domain.Sort;
|
||||
@@ -19,31 +15,28 @@ import run.halo.app.extension.GroupVersion;
|
||||
import run.halo.app.extension.ListOptions;
|
||||
import run.halo.app.extension.PageRequestImpl;
|
||||
import run.halo.app.extension.ReactiveExtensionClient;
|
||||
import run.halo.app.extension.router.selector.FieldSelector;
|
||||
import run.halo.app.extension.index.query.Condition;
|
||||
import run.halo.app.extension.index.query.Queries;
|
||||
import run.halo.operationaudit.audit.AuditLog;
|
||||
|
||||
/**
|
||||
* 自有查询端点(技术方案 5.3 / 风险项 #2):
|
||||
* 自有查询/导出端点(技术方案 5.3 / 风险项 #2):
|
||||
*
|
||||
* <p>经源码级验证(v2.26.1 FieldSelectorConverter),Halo 原生列表 API 的 fieldSelector
|
||||
* 仅支持 =/!=/IN 等值操作符,不支持时间区间与模糊匹配,因此按技术方案预案启用插件自有
|
||||
* 查询端点,内部走索引 Query 实现(无内存分页),UI 调用方式不变。
|
||||
*
|
||||
* <p>筛选条件构造抽到 {@link AuditLogFilters} 供查询(分页 JSON)与导出(全量 CSV,
|
||||
* 见 {@link AuditLogCsvExporter})共用。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class AuditQueryEndpoint implements CustomEndpoint {
|
||||
|
||||
/** fieldSelector 支持等值筛选的字段白名单(与已注册索引一一对应)。 */
|
||||
private static final Set<String> FILTERABLE_FIELDS =
|
||||
Set.of("spec.username", "spec.resourceType", "spec.method", "spec.statusCode");
|
||||
|
||||
/** 每页大小上限,防止误用拖垮查询。 */
|
||||
static final int MAX_PAGE_SIZE = 100;
|
||||
|
||||
private final ReactiveExtensionClient client;
|
||||
private final AuditLogCsvExporter csvExporter;
|
||||
|
||||
@Override
|
||||
public GroupVersion groupVersion() {
|
||||
@@ -59,6 +52,12 @@ public class AuditQueryEndpoint implements CustomEndpoint {
|
||||
+ "关键字(resourceName/path 模糊)、结果(success/failure)、"
|
||||
+ "时间区间(含边界)")
|
||||
.build())
|
||||
.GET("auditlogs/-/export", this::export, builder -> builder
|
||||
.operationId("ExportAuditLogs")
|
||||
.description("按筛选条件导出审计日志为 CSV 附件(UTF-8 BOM,Excel/WPS "
|
||||
+ "可直接打开):筛选参数与 query 完全一致,不分页全量导出,"
|
||||
+ "按时间升序输出")
|
||||
.build())
|
||||
.build();
|
||||
}
|
||||
|
||||
@@ -69,77 +68,29 @@ public class AuditQueryEndpoint implements CustomEndpoint {
|
||||
var size = Math.min(Math.max(parseInt(params.getFirst("size"), 20), 1), MAX_PAGE_SIZE);
|
||||
var sort = parseSort(params.getFirst("sort"));
|
||||
|
||||
var conditions = new ArrayList<Condition>();
|
||||
|
||||
// fieldSelector 等值筛选:field=value(多个 fieldSelector 参数叠加 AND)
|
||||
for (var term : params.getOrDefault("fieldSelector", List.of())) {
|
||||
var idx = term.indexOf('=');
|
||||
if (idx <= 0) {
|
||||
return badRequest("Invalid fieldSelector term, expect field=value: " + term);
|
||||
}
|
||||
var field = term.substring(0, idx).trim();
|
||||
var value = term.substring(idx + 1).trim();
|
||||
if (!FILTERABLE_FIELDS.contains(field)) {
|
||||
return badRequest("Field not filterable: " + field);
|
||||
}
|
||||
conditions.add(Queries.equal(field, value));
|
||||
}
|
||||
|
||||
// 关键字:资源名称 / 完整路径 模糊匹配(OR)
|
||||
var keyword = params.getFirst("keyword");
|
||||
if (StringUtils.hasText(keyword)) {
|
||||
var kw = keyword.trim();
|
||||
conditions.add(Queries.or(
|
||||
Queries.contains("spec.resourceName", kw),
|
||||
Queries.contains("spec.path", kw)));
|
||||
}
|
||||
|
||||
// 结果筛选:success = 2xx/3xx,failure = 4xx/5xx
|
||||
var resultFilter = params.getFirst("result");
|
||||
if (StringUtils.hasText(resultFilter)) {
|
||||
switch (resultFilter.trim().toLowerCase()) {
|
||||
case "success" -> {
|
||||
conditions.add(Queries.greaterThan("spec.statusCode", "200", true));
|
||||
conditions.add(Queries.lessThan("spec.statusCode", "400", true));
|
||||
}
|
||||
case "failure" -> conditions.add(Queries.greaterThan("spec.statusCode", "400", true));
|
||||
default -> {
|
||||
return badRequest("Invalid result, expect success or failure: "
|
||||
+ resultFilter);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 时间区间(含边界,ISO-8601 Instant)
|
||||
ListOptions options;
|
||||
try {
|
||||
var start = parseInstant(params.getFirst("startTime"));
|
||||
var end = parseInstant(params.getFirst("endTime"));
|
||||
if (start != null) {
|
||||
conditions.add(Queries.greaterThan("metadata.creationTimestamp",
|
||||
start.toString(), true));
|
||||
}
|
||||
if (end != null) {
|
||||
conditions.add(Queries.lessThan("metadata.creationTimestamp",
|
||||
end.toString(), true));
|
||||
}
|
||||
} catch (DateTimeParseException e) {
|
||||
return badRequest("Invalid time format, expect ISO-8601 instant: "
|
||||
+ e.getMessage());
|
||||
options = AuditLogFilters.fromQueryParams(params);
|
||||
} catch (IllegalArgumentException e) {
|
||||
return badRequest(e.getMessage());
|
||||
}
|
||||
|
||||
var options = conditions.isEmpty()
|
||||
? new ListOptions().setFieldSelector(FieldSelector.all())
|
||||
: new ListOptions().setFieldSelector(
|
||||
FieldSelector.of(conditions.size() == 1 ? conditions.get(0)
|
||||
: Queries.and(conditions.get(0),
|
||||
conditions.subList(1, conditions.size())
|
||||
.toArray(Condition[]::new))));
|
||||
|
||||
var pageable = PageRequestImpl.of(page, size, sort);
|
||||
return client.listBy(AuditLog.class, options, pageable)
|
||||
.flatMap(result -> ServerResponse.ok().bodyValue(result));
|
||||
}
|
||||
|
||||
/** 导出端点:筛选参数与 query 一致,全量流式 CSV 附件下载。 */
|
||||
private Mono<ServerResponse> export(ServerRequest request) {
|
||||
ListOptions options;
|
||||
try {
|
||||
options = AuditLogFilters.fromQueryParams(request.queryParams());
|
||||
} catch (IllegalArgumentException e) {
|
||||
return badRequest(e.getMessage());
|
||||
}
|
||||
return csvExporter.exportResponse(options);
|
||||
}
|
||||
|
||||
private static Mono<ServerResponse> badRequest(String message) {
|
||||
return ServerResponse.badRequest().bodyValue(java.util.Map.of("message", message));
|
||||
}
|
||||
@@ -169,11 +120,4 @@ public class AuditQueryEndpoint implements CustomEndpoint {
|
||||
var descending = parts.length < 2 || !"asc".equalsIgnoreCase(parts[1].trim());
|
||||
return Sort.by(descending ? Sort.Order.desc(field) : Sort.Order.asc(field));
|
||||
}
|
||||
|
||||
private static Instant parseInstant(String value) {
|
||||
if (!StringUtils.hasText(value)) {
|
||||
return null;
|
||||
}
|
||||
return Instant.parse(value.trim());
|
||||
}
|
||||
}
|
||||
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 操作描述(这条操作真正干了什么):由 method / resourceType / path 推导中文短语,
|
||||
* 如 登录、登出、新建用户、修改文章、发布文章、启用插件、修改密码。
|
||||
*
|
||||
* <p>与前端 {@code ui/src/utils/audit.ts} 的 {@code describeOperation} 保持一致
|
||||
* (同一套 RESOURCE_LABELS / METHOD_VERBS / SUB_ACTION_VERBS / SUB_ACTION_PHRASES
|
||||
* 映射与子动作解析规则),两处需同步修改。推导纯用于展示/导出,不落库:
|
||||
* 历史记录同样适用;未识别的子动作回退为「动词 + 资源名」,
|
||||
* 未识别的资源类型直接使用原始 resourceType。
|
||||
*/
|
||||
final class OperationDescription {
|
||||
|
||||
/** 资源类型的中文展示名(未知类型回退原始值)。 */
|
||||
private static final Map<String, String> RESOURCE_LABELS = Map.ofEntries(
|
||||
Map.entry("posts", "文章"),
|
||||
Map.entry("singlepages", "页面"),
|
||||
Map.entry("comments", "评论"),
|
||||
Map.entry("replies", "回复"),
|
||||
Map.entry("users", "用户"),
|
||||
Map.entry("roles", "角色"),
|
||||
Map.entry("settings", "设置"),
|
||||
Map.entry("configmaps", "配置"),
|
||||
Map.entry("plugins", "插件"),
|
||||
Map.entry("themes", "主题"),
|
||||
Map.entry("attachments", "附件"),
|
||||
Map.entry("menus", "菜单"),
|
||||
Map.entry("categories", "分类"),
|
||||
Map.entry("tags", "标签"));
|
||||
|
||||
/** 动作方法的基础动词(未知方法回退原始值)。 */
|
||||
private static final Map<String, String> METHOD_VERBS = Map.of(
|
||||
"POST", "新建",
|
||||
"PUT", "修改",
|
||||
"PATCH", "修改",
|
||||
"DELETE", "删除",
|
||||
"GET", "查看");
|
||||
|
||||
/**
|
||||
* 子资源动作段({@code /apis/.../{plural}/{name}/{action}} 的 action)→ 动词,
|
||||
* 与资源名拼接成短语,如 publish + 文章 = 发布文章。
|
||||
*/
|
||||
private static final Map<String, String> SUB_ACTION_VERBS = Map.ofEntries(
|
||||
Map.entry("publish", "发布"),
|
||||
Map.entry("unpublish", "取消发布"),
|
||||
Map.entry("recycle", "移入回收站"),
|
||||
Map.entry("restore", "恢复"),
|
||||
Map.entry("enable", "启用"),
|
||||
Map.entry("disable", "停用"),
|
||||
Map.entry("upgrade", "升级"),
|
||||
Map.entry("uninstall", "卸载"),
|
||||
Map.entry("reload", "重载"),
|
||||
Map.entry("activation", "启用"),
|
||||
Map.entry("reply", "回复"),
|
||||
Map.entry("recalculate", "重新统计"));
|
||||
|
||||
/** 子资源动作段 → 完整短语(不拼接资源名)。 */
|
||||
private static final Map<String, String> SUB_ACTION_PHRASES = Map.of(
|
||||
"password", "修改密码",
|
||||
"resetpassword", "重置密码");
|
||||
|
||||
private OperationDescription() {
|
||||
}
|
||||
|
||||
/** 推导操作中文描述。 */
|
||||
static String describe(String method, String resourceType, String path) {
|
||||
var cleanPath = pathWithoutQuery(path);
|
||||
if ("auth".equals(resourceType) || "/login".equals(cleanPath)
|
||||
|| "/logout".equals(cleanPath)) {
|
||||
if ("/login".equals(cleanPath)) {
|
||||
return "登录";
|
||||
}
|
||||
if ("/logout".equals(cleanPath)) {
|
||||
return "登出";
|
||||
}
|
||||
return "认证操作";
|
||||
}
|
||||
var label = RESOURCE_LABELS.getOrDefault(resourceType, resourceType);
|
||||
var verb = METHOD_VERBS.getOrDefault(method, method);
|
||||
// /apis/{group}/{version}/{plural}/{name}/{action}:
|
||||
// 去掉空段后 segments 为 [apis, group, version, plural, name, action],
|
||||
// 子动作段为 segments[5]
|
||||
var segments = Arrays.stream(cleanPath.split("/"))
|
||||
.filter(segment -> !segment.isEmpty())
|
||||
.toArray(String[]::new);
|
||||
var action = segments.length >= 6 ? segments[5].toLowerCase() : null;
|
||||
if (action != null) {
|
||||
var phrase = SUB_ACTION_PHRASES.get(action);
|
||||
if (phrase != null) {
|
||||
return phrase;
|
||||
}
|
||||
var subVerb = SUB_ACTION_VERBS.get(action);
|
||||
if (subVerb != null) {
|
||||
return subVerb + label;
|
||||
}
|
||||
}
|
||||
return verb + label;
|
||||
}
|
||||
|
||||
/** 剥离路径的查询串(spec.path 存的是含查询串的完整路径)。 */
|
||||
private static String pathWithoutQuery(String path) {
|
||||
if (path == null || path.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
var queryStart = path.indexOf('?');
|
||||
return queryStart >= 0 ? path.substring(0, queryStart) : path;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user