|
|
@@ -0,0 +1,209 @@
|
|
|
+package com.zsjz.ai.module.skill.controller;
|
|
|
+
|
|
|
+import com.fasterxml.jackson.databind.JsonNode;
|
|
|
+import com.fasterxml.jackson.databind.ObjectMapper;
|
|
|
+import com.fasterxml.jackson.databind.node.ArrayNode;
|
|
|
+import com.fasterxml.jackson.databind.node.ObjectNode;
|
|
|
+import com.zsjz.ai.common.constants.PathConst;
|
|
|
+import com.zsjz.ai.common.exception.ServerException;
|
|
|
+import org.springframework.beans.factory.annotation.Autowired;
|
|
|
+import org.springframework.http.CacheControl;
|
|
|
+import org.springframework.http.MediaType;
|
|
|
+import org.springframework.http.ResponseEntity;
|
|
|
+import org.springframework.web.bind.annotation.GetMapping;
|
|
|
+import org.springframework.web.bind.annotation.PathVariable;
|
|
|
+import org.springframework.web.bind.annotation.RequestMapping;
|
|
|
+import org.springframework.web.bind.annotation.RestController;
|
|
|
+import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
|
|
|
+
|
|
|
+import java.io.File;
|
|
|
+import java.io.IOException;
|
|
|
+import java.nio.charset.StandardCharsets;
|
|
|
+import java.nio.file.Files;
|
|
|
+import java.nio.file.Path;
|
|
|
+import java.util.ArrayList;
|
|
|
+import java.util.List;
|
|
|
+import java.util.regex.Pattern;
|
|
|
+import java.util.stream.Stream;
|
|
|
+
|
|
|
+/**
|
|
|
+ * 本机技能市场:目录与技能文档。
|
|
|
+ *
|
|
|
+ * <p>桌面端在主进程里匿名读取这两个接口,因此 {@code /skill/**} 必须加入
|
|
|
+ * Sa-Token 白名单。数据属于系统资产,路径由
|
|
|
+ * {@link PathConst#SKILL_MARKET_PATH} 维护:
|
|
|
+ * {@code qingjian/system/skill-market} 下的 {@code catalog.json} 与
|
|
|
+ * {@code documents/}。
|
|
|
+ *
|
|
|
+ * <p>目录里的 {@code url} 保存为相对路径({@code document/...}),响应时按
|
|
|
+ * 当前请求的主机与 context-path 改写为绝对地址,因此换端口或部署路径无需
|
|
|
+ * 重新生成目录。
|
|
|
+ */
|
|
|
+@RestController
|
|
|
+@RequestMapping("/skill")
|
|
|
+public class SkillMarketController {
|
|
|
+
|
|
|
+ /** 与桌面端 {@code expandSkillResources} 的内联顺序、数量上限保持一致。 */
|
|
|
+ private static final int MAX_RESOURCES = 20;
|
|
|
+
|
|
|
+ /** 任意层级的 {@code SKILL.md} 都不作为附件再次内联。 */
|
|
|
+ private static final Pattern SKILL_FILE = Pattern.compile("(?:^|/)SKILL\\.md$");
|
|
|
+
|
|
|
+ private static final MediaType MARKDOWN =
|
|
|
+ MediaType.parseMediaType("text/markdown;charset=UTF-8");
|
|
|
+
|
|
|
+ private final ObjectMapper objectMapper;
|
|
|
+ private final Path marketRoot;
|
|
|
+
|
|
|
+ @Autowired
|
|
|
+ public SkillMarketController(ObjectMapper objectMapper) {
|
|
|
+ this(objectMapper, PathConst.SKILL_MARKET_PATH);
|
|
|
+ }
|
|
|
+
|
|
|
+ /** 测试可注入临时目录,避免依赖进程工作目录下的系统资产。 */
|
|
|
+ SkillMarketController(ObjectMapper objectMapper, Path marketRoot) {
|
|
|
+ this.objectMapper = objectMapper;
|
|
|
+ this.marketRoot = marketRoot.toAbsolutePath().normalize();
|
|
|
+ }
|
|
|
+
|
|
|
+ /** 市场目录;桌面端用它展示技能列表。 */
|
|
|
+ @GetMapping("/catalog.json")
|
|
|
+ public ResponseEntity<JsonNode> catalog() {
|
|
|
+ Path file = catalogPath();
|
|
|
+ if (!Files.isRegularFile(file)) {
|
|
|
+ throw new ServerException(404, "技能市场目录不存在");
|
|
|
+ }
|
|
|
+ try {
|
|
|
+ JsonNode catalog = objectMapper.readTree(file.toFile());
|
|
|
+ rewriteDocumentUrls(catalog);
|
|
|
+ return ResponseEntity.ok()
|
|
|
+ .contentType(MediaType.APPLICATION_JSON)
|
|
|
+ .cacheControl(CacheControl.noCache())
|
|
|
+ .body(catalog);
|
|
|
+ } catch (IOException error) {
|
|
|
+ throw new ServerException(503, "技能市场目录无法读取");
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 单个技能文档。
|
|
|
+ *
|
|
|
+ * <p>{@code SKILL.md} 会按桌面端的附件规则,把同目录(含子目录)最多
|
|
|
+ * {@value #MAX_RESOURCES} 个其它 {@code .md} 以围栏代码块追加到正文;
|
|
|
+ * 其它文档原样返回。
|
|
|
+ */
|
|
|
+ @GetMapping("/document/{*path}")
|
|
|
+ public ResponseEntity<String> document(@PathVariable("path") String path) {
|
|
|
+ String relative = normalizeRelativePath(path);
|
|
|
+ Path documentsRoot = documentsRoot();
|
|
|
+ Path file = documentsRoot.resolve(relative).normalize();
|
|
|
+ if (!file.startsWith(documentsRoot) || !Files.isRegularFile(file)) {
|
|
|
+ throw new ServerException(404, "技能文档不存在");
|
|
|
+ }
|
|
|
+ try {
|
|
|
+ String body = Files.readString(file, StandardCharsets.UTF_8);
|
|
|
+ if ("SKILL.md".equals(file.getFileName().toString())) {
|
|
|
+ body = appendResources(file.getParent(), documentsRoot, body);
|
|
|
+ }
|
|
|
+ return ResponseEntity.ok()
|
|
|
+ .contentType(MARKDOWN)
|
|
|
+ .cacheControl(CacheControl.noCache())
|
|
|
+ .body(body);
|
|
|
+ } catch (IOException error) {
|
|
|
+ throw new ServerException(503, "技能文档无法读取");
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ private Path catalogPath() {
|
|
|
+ return marketRoot.resolve("catalog.json");
|
|
|
+ }
|
|
|
+
|
|
|
+ private Path documentsRoot() {
|
|
|
+ return marketRoot.resolve("documents");
|
|
|
+ }
|
|
|
+
|
|
|
+ /** 相对地址 -> 当前主机的绝对地址;已经是绝对地址的条目保持不变。 */
|
|
|
+ private void rewriteDocumentUrls(JsonNode catalog) {
|
|
|
+ JsonNode skills = catalog.path("skills");
|
|
|
+ if (!(skills instanceof ArrayNode entries)) return;
|
|
|
+ String base = ServletUriComponentsBuilder.fromCurrentContextPath()
|
|
|
+ .path("/skill/")
|
|
|
+ .toUriString();
|
|
|
+ for (JsonNode candidate : entries) {
|
|
|
+ if (!(candidate instanceof ObjectNode entry)) continue;
|
|
|
+ String url = entry.path("url").asText("").trim();
|
|
|
+ if (url.isEmpty()
|
|
|
+ || url.startsWith("http://")
|
|
|
+ || url.startsWith("https://")
|
|
|
+ || url.startsWith("file://")) {
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+ entry.put("url", base + url.replaceFirst("^/+", ""));
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 文档路径只接受 {@code .md},且不允许空段、点段、反斜杠或越界。
|
|
|
+ * 返回相对 documents 根目录的路径。
|
|
|
+ */
|
|
|
+ private static String normalizeRelativePath(String path) {
|
|
|
+ String relative = path == null ? "" : path.replaceFirst("^/+", "").replaceFirst("/+$", "");
|
|
|
+ if (relative.isEmpty()
|
|
|
+ || relative.contains("\\")
|
|
|
+ || relative.indexOf('\0') >= 0
|
|
|
+ || !relative.endsWith(".md")) {
|
|
|
+ throw new ServerException(400, "非法的技能文档路径");
|
|
|
+ }
|
|
|
+ for (String segment : relative.split("/")) {
|
|
|
+ if (segment.isEmpty() || ".".equals(segment) || "..".equals(segment)) {
|
|
|
+ throw new ServerException(400, "非法的技能文档路径");
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return relative;
|
|
|
+ }
|
|
|
+
|
|
|
+ /** 与桌面端 `expandSkillResources` 完全一致的附件拼接格式。 */
|
|
|
+ private String appendResources(Path skillDir, Path documentsRoot, String body) {
|
|
|
+ List<String> siblings = new ArrayList<>();
|
|
|
+ try (Stream<Path> stream = Files.walk(skillDir)) {
|
|
|
+ siblings = stream
|
|
|
+ .filter(Files::isRegularFile)
|
|
|
+ .map(file -> documentsRoot.relativize(file).toString()
|
|
|
+ .replace(File.separatorChar, '/'))
|
|
|
+ .filter(name -> name.endsWith(".md"))
|
|
|
+ .filter(name -> !SKILL_FILE.matcher(name).find())
|
|
|
+ .sorted()
|
|
|
+ .limit(MAX_RESOURCES)
|
|
|
+ .toList();
|
|
|
+ } catch (IOException error) {
|
|
|
+ // 附件列表读不到时退化为单文档,不阻塞安装预览。
|
|
|
+ return body;
|
|
|
+ }
|
|
|
+ if (siblings.isEmpty()) return body;
|
|
|
+
|
|
|
+ StringBuilder out = new StringBuilder(stripTrailingWhitespace(body));
|
|
|
+ for (String sibling : siblings) {
|
|
|
+ Path file = documentsRoot.resolve(sibling);
|
|
|
+ try {
|
|
|
+ String content = Files.readString(file, StandardCharsets.UTF_8);
|
|
|
+ String label = skillDir.relativize(file).toString()
|
|
|
+ .replace(File.separatorChar, '/');
|
|
|
+ out.append("\n\n---\n\n# Attached resource: ").append(label)
|
|
|
+ .append("\n\n```\n")
|
|
|
+ .append(stripTrailingWhitespace(content))
|
|
|
+ .append("\n```");
|
|
|
+ } catch (IOException error) {
|
|
|
+ // 单个附件读失败只丢弃该附件,与桌面端 jsDelivr 列表失败降级一致。
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return out.append("\n").toString();
|
|
|
+ }
|
|
|
+
|
|
|
+ private static String stripTrailingWhitespace(String value) {
|
|
|
+ int end = value.length();
|
|
|
+ while (end > 0 && Character.isWhitespace(value.charAt(end - 1))) {
|
|
|
+ end -= 1;
|
|
|
+ }
|
|
|
+ return value.substring(0, end);
|
|
|
+ }
|
|
|
+}
|