diff --git a/.gitignore b/.gitignore index 90f9a26..90de064 100644 --- a/.gitignore +++ b/.gitignore @@ -22,6 +22,9 @@ gradle-app.setting # 本地配置 local.properties +# 服务端本地运行时的布局数据 +ComposeRemoteServer/data/ + # 上游只读第三方仓库(不纳入本仓库版本管理) remotecompose/ remotecompose-android/ diff --git a/ComposeRemoteServer/k8s/deploy.yaml b/ComposeRemoteServer/k8s/deploy.yaml index 73d496c..6ea1c8d 100644 --- a/ComposeRemoteServer/k8s/deploy.yaml +++ b/ComposeRemoteServer/k8s/deploy.yaml @@ -22,7 +22,7 @@ spec: spec: containers: - name: server - image: composeremote/server:1.0.0-layout2 + image: composeremote/server:1.0.0-editor2 imagePullPolicy: Never ports: - name: http @@ -30,6 +30,13 @@ spec: env: - name: JAVA_TOOL_OPTIONS value: "-XX:MaxRAMPercentage=60 -XX:+ExitOnOutOfMemoryError" + - name: LAYOUT_DIR + value: /app/data/layouts + - name: ASSETS_DIR + value: /app/data/assets + volumeMounts: + - name: layouts + mountPath: /app/data resources: requests: cpu: 100m @@ -47,6 +54,12 @@ spec: port: 8000 initialDelaySeconds: 30 periodSeconds: 20 + volumes: + # 布局 JSON 落在宿主机,Pod 重建 / 镜像升级不丢数据。 + - name: layouts + hostPath: + path: /opt/composeremote/data + type: DirectoryOrCreate --- apiVersion: v1 kind: Service diff --git a/ComposeRemoteServer/pom.xml b/ComposeRemoteServer/pom.xml index 9f7822b..f963310 100644 --- a/ComposeRemoteServer/pom.xml +++ b/ComposeRemoteServer/pom.xml @@ -45,6 +45,11 @@ com.fasterxml.jackson.core jackson-databind + + + com.fasterxml.jackson.module + jackson-module-kotlin + org.springframework.boot diff --git a/ComposeRemoteServer/src/main/java/com/ttstd/composeremote/server/controller/EditorPageController.java b/ComposeRemoteServer/src/main/java/com/ttstd/composeremote/server/controller/EditorPageController.java new file mode 100644 index 0000000..7084808 --- /dev/null +++ b/ComposeRemoteServer/src/main/java/com/ttstd/composeremote/server/controller/EditorPageController.java @@ -0,0 +1,27 @@ +package com.ttstd.composeremote.server.controller; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.http.CacheControl; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; + +/** + * 布局编辑器页面。 + * + *

编辑器是单文件 HTML;静态资源统一配置了 30 天缓存, + * 这里单独关掉缓存,方便改完编辑器刷新就生效。 + */ +@Controller +public class EditorPageController { + + @GetMapping({"/editor", "/editor/"}) + public ResponseEntity editor() { + return ResponseEntity.ok() + .contentType(MediaType.parseMediaType("text/html;charset=UTF-8")) + .cacheControl(CacheControl.noCache()) + .body(new ClassPathResource("static/editor.html")); + } +} diff --git a/ComposeRemoteServer/src/main/java/com/ttstd/composeremote/server/controller/LayoutAdminController.java b/ComposeRemoteServer/src/main/java/com/ttstd/composeremote/server/controller/LayoutAdminController.java new file mode 100644 index 0000000..8097fcd --- /dev/null +++ b/ComposeRemoteServer/src/main/java/com/ttstd/composeremote/server/controller/LayoutAdminController.java @@ -0,0 +1,80 @@ +package com.ttstd.composeremote.server.controller; + +import com.ttstd.composeremote.server.layout.LayoutDocument; +import com.ttstd.composeremote.server.layout.LayoutStore; +import org.springframework.http.HttpStatus; +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.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.server.ResponseStatusException; + +import java.util.List; +import java.util.Map; + +/** + * 布局编辑接口,供后台拖拽编辑器读写。 + * + *

布局以 JSON 落盘(目录由 {@code app.layout-dir} / {@code LAYOUT_DIR} 指定), + * 保存后下一次 {@code GET /api/remote-ui/{page}} 就会编译新布局下发。 + * 当前演示环境不鉴权。 + */ +@RestController +@RequestMapping("/api/layouts") +public class LayoutAdminController { + + /** 布局列表,编辑器启动时用来发现页面。 */ + @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE) + public List list() { + return LayoutStore.INSTANCE.all().stream() + .map(document -> new LayoutSummary( + document.getId(), + document.getTitle(), + document.getItems().size() + )) + .toList(); + } + + /** 读取单个布局;不存在返回 404。 */ + @GetMapping(value = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE) + public LayoutDocument get(@PathVariable("id") String id) { + LayoutDocument document = LayoutStore.INSTANCE.get(id); + if (document == null) { + throw new ResponseStatusException(HttpStatus.NOT_FOUND, "布局不存在: " + id); + } + return document; + } + + /** + * 保存布局。 + * + *

以路径上的 id 为准,避免请求体里的 id 与路径不一致; + * 校验失败返回 400,错误信息是直接给编辑器展示的中文提示。 + */ + @PutMapping(value = "/{id}", consumes = MediaType.APPLICATION_JSON_VALUE, + produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity save(@PathVariable("id") String id, + @RequestBody LayoutDocument body) { + LayoutDocument document = new LayoutDocument( + id, + body.getTitle(), + body.getCanvas(), + body.getBackgroundColor(), + body.getItems() + ); + try { + LayoutStore.INSTANCE.put(document); + } catch (IllegalArgumentException e) { + return ResponseEntity.badRequest().body(Map.of("error", e.getMessage())); + } + return ResponseEntity.ok(document); + } + + /** 布局摘要。 */ + public record LayoutSummary(String id, String title, int items) { + } +} diff --git a/ComposeRemoteServer/src/main/java/com/ttstd/composeremote/server/controller/RemoteUIController.java b/ComposeRemoteServer/src/main/java/com/ttstd/composeremote/server/controller/RemoteUIController.java index 7228d02..d552f2f 100644 --- a/ComposeRemoteServer/src/main/java/com/ttstd/composeremote/server/controller/RemoteUIController.java +++ b/ComposeRemoteServer/src/main/java/com/ttstd/composeremote/server/controller/RemoteUIController.java @@ -2,6 +2,7 @@ package com.ttstd.composeremote.server.controller; import com.ttstd.composeremote.server.RemoteDocumentBuilderKt; import com.ttstd.composeremote.server.layout.LayoutPages; +import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.ClassPathResource; import org.springframework.http.CacheControl; import org.springframework.http.HttpStatus; @@ -14,8 +15,11 @@ import org.springframework.web.bind.annotation.RestController; import org.springframework.web.server.ResponseStatusException; import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; import java.time.Duration; import java.util.List; +import java.util.Locale; /** * 服务端驱动 UI 接口。 @@ -35,6 +39,10 @@ import java.util.List; @RequestMapping("/api/remote-ui") public class RemoteUIController { + /** 图片资源目录,优先于 classpath 里的内置资源;容器中由 ASSETS_DIR 指向挂载卷。 */ + @Value("${app.assets-dir:./data/assets}") + private String assetsDir; + @GetMapping( value = {"/{page}", ""}, produces = MediaType.APPLICATION_OCTET_STREAM_VALUE @@ -60,20 +68,50 @@ public class RemoteUIController { /** * 页面引用的图片资源。 * - *

图片 URL 带内容标识时,可以在此长期缓存;当前先固定 30 天。 + *

先找外部资源目录({@code app.assets-dir},默认 {@code ./data/assets}), + * 找不到再回落到 classpath 内置图片。图片 URL 带内容标识时,可以在此长期缓存;当前先固定 30 天。 */ - @GetMapping(value = "/assets/{name:.+}", produces = MediaType.IMAGE_PNG_VALUE) + @GetMapping(value = "/assets/{name:.+}") public ResponseEntity getAsset(@PathVariable("name") String name) throws IOException { if (!name.matches("[A-Za-z0-9._-]+")) { throw new ResponseStatusException(HttpStatus.NOT_FOUND); } - ClassPathResource resource = new ClassPathResource("static/api/" + name); - if (!resource.exists()) { - throw new ResponseStatusException(HttpStatus.NOT_FOUND); + byte[] body = readExternalAsset(name); + if (body == null) { + ClassPathResource resource = new ClassPathResource("static/api/" + name); + if (!resource.exists()) { + throw new ResponseStatusException(HttpStatus.NOT_FOUND); + } + body = resource.getContentAsByteArray(); } return ResponseEntity.ok() - .contentType(MediaType.IMAGE_PNG) + .contentType(mediaTypeFor(name)) .cacheControl(CacheControl.maxAge(Duration.ofDays(30)).cachePublic()) - .body(resource.getContentAsByteArray()); + .body(body); + } + + /** 读取外部图片目录里的文件;不存在或越界时返回 null。 */ + private byte[] readExternalAsset(String name) throws IOException { + Path directory = Path.of(assetsDir).toAbsolutePath().normalize(); + Path file = directory.resolve(name).normalize(); + if (!file.startsWith(directory) || !Files.isRegularFile(file)) { + return null; + } + return Files.readAllBytes(file); + } + + /** 按扩展名给出图片类型,Android 端解码与浏览器预览都依赖正确的 Content-Type。 */ + private static MediaType mediaTypeFor(String name) { + String lower = name.toLowerCase(Locale.ROOT); + if (lower.endsWith(".jpg") || lower.endsWith(".jpeg")) { + return MediaType.IMAGE_JPEG; + } + if (lower.endsWith(".webp")) { + return MediaType.parseMediaType("image/webp"); + } + if (lower.endsWith(".gif")) { + return MediaType.IMAGE_GIF; + } + return MediaType.IMAGE_PNG; } } diff --git a/ComposeRemoteServer/src/main/kotlin/com/ttstd/composeremote/server/config/LayoutStoreConfiguration.kt b/ComposeRemoteServer/src/main/kotlin/com/ttstd/composeremote/server/config/LayoutStoreConfiguration.kt new file mode 100644 index 0000000..e575f0a --- /dev/null +++ b/ComposeRemoteServer/src/main/kotlin/com/ttstd/composeremote/server/config/LayoutStoreConfiguration.kt @@ -0,0 +1,19 @@ +package com.ttstd.composeremote.server.config + +import com.ttstd.composeremote.server.layout.LayoutStore +import jakarta.annotation.PostConstruct +import org.springframework.beans.factory.annotation.Value +import org.springframework.context.annotation.Configuration +import java.nio.file.Path + +/** 启动时把布局目录(默认 `./data/layouts`,可用 `LAYOUT_DIR` 覆盖)交给 [LayoutStore]。 */ +@Configuration(proxyBeanMethods = false) +class LayoutStoreConfiguration( + @Value("\${app.layout-dir:./data/layouts}") private val layoutDir: String, +) { + + @PostConstruct + fun init() { + LayoutStore.initialize(Path.of(layoutDir)) + } +} diff --git a/ComposeRemoteServer/src/main/kotlin/com/ttstd/composeremote/server/layout/LayoutStore.kt b/ComposeRemoteServer/src/main/kotlin/com/ttstd/composeremote/server/layout/LayoutStore.kt index 7899ccf..59cef6b 100644 --- a/ComposeRemoteServer/src/main/kotlin/com/ttstd/composeremote/server/layout/LayoutStore.kt +++ b/ComposeRemoteServer/src/main/kotlin/com/ttstd/composeremote/server/layout/LayoutStore.kt @@ -1,25 +1,121 @@ package com.ttstd.composeremote.server.layout +import com.fasterxml.jackson.databind.ObjectMapper +import com.fasterxml.jackson.databind.SerializationFeature +import com.fasterxml.jackson.module.kotlin.registerKotlinModule +import org.slf4j.LoggerFactory +import java.nio.file.Files +import java.nio.file.Path +import java.nio.file.StandardCopyOption +import java.util.concurrent.ConcurrentHashMap + /** - * 布局文档的内存存储。 + * 布局文档存储。 * - * 当前先内置一份桌面布局,后续接入后台编辑器时,把保存结果 [put] 进来即可, + * 文档以 JSON 文件落在磁盘目录(默认 `./data/layouts`,可用 `LAYOUT_DIR` 覆盖), + * 启动时整体加载进内存,保存时先写临时文件再原子替换,避免写一半留下坏文件。 * 页面接口仍然走 [LayoutCompiler] 编译,客户端无需感知存储实现。 */ object LayoutStore { - private val layouts = mutableMapOf() + private val log = LoggerFactory.getLogger(LayoutStore::class.java) - init { - put(desktopLayout()) + private val mapper = ObjectMapper() + .registerKotlinModule() + .enable(SerializationFeature.INDENT_OUTPUT) + + private val layouts = ConcurrentHashMap() + + @Volatile + private var dir: Path? = null + + /** 由 Spring 启动时调用:加载目录下已有布局,缺失桌面布局时写入默认布局。 */ + @Synchronized + fun initialize(directory: Path) { + Files.createDirectories(directory) + dir = directory + + Files.list(directory).use { stream -> + stream.filter { it.fileName.toString().endsWith(".json") } + .forEach { file -> + runCatching { mapper.readValue(file.toFile(), LayoutDocument::class.java) } + .onSuccess { document -> layouts[document.id] = document } + .onFailure { log.warn("布局文件读取失败: {}", file, it) } + } + } + + if (layouts[DESKTOP_PAGE] == null) { + val default = desktopLayout() + layouts[default.id] = default + persist(default) + log.info("写入默认布局: {}", fileOf(default.id)) + } + log.info("布局已加载 {} 个,目录: {}", layouts.size, directory.toAbsolutePath()) } fun get(id: String): LayoutDocument? = layouts[id] + fun all(): List = layouts.values.sortedBy { it.id } + + /** 校验并保存布局;校验不通过时抛 [IllegalArgumentException]。 */ fun put(document: LayoutDocument) { + validate(document) layouts[document.id] = document + persist(document) } + /** 校验布局的坐标范围、组件 id 与点击行为,错误信息直接返回给编辑器。 */ + private fun validate(document: LayoutDocument) { + require(document.id.matches(LAYOUT_ID)) { + "布局 id 只能包含字母、数字、下划线和短横线: ${document.id}" + } + require(document.title.isNotBlank() && document.title.length <= 100) { + "页面标题不能为空且不超过 100 个字符" + } + require(document.canvas.aspectWidth > 0 && document.canvas.aspectHeight > 0) { + "画布宽高比必须大于 0" + } + require(document.canvas.columns in 1..24) { "网格列数需在 1..24 之间" } + require(document.items.size <= 200) { "单页组件不能超过 200 个" } + + val ids = HashSet() + document.items.forEachIndexed { index, item -> + val label = "第 ${index + 1} 个组件(${item.id})" + require(item.id.matches(LAYOUT_ID)) { "$label: id 只能包含字母、数字、下划线和短横线" } + require(ids.add(item.id)) { "$label: id 重复" } + require(item.x in 0..999 && item.y in 0..999) { "$label: x、y 需在 0..999" } + require(item.w in 1..1000 && item.h in 1..1000) { "$label: w、h 需在 1..1000" } + require(item.x + item.w <= 1000) { "$label: x + w 超过 1000" } + require(item.y + item.h <= 1000) { "$label: y + h 超过 1000" } + item.action?.let { action -> + require(action.target.isNotBlank()) { "$label: 点击目标不能为空" } + } + } + } + + /** 原子写入单个布局文件:先写 `.tmp`,再替换目标文件。 */ + private fun persist(document: LayoutDocument) { + val directory = dir ?: return + val target = fileOf(document.id) + Files.createDirectories(directory) + val temp = target.resolveSibling("${document.id}.json.tmp") + mapper.writeValue(temp.toFile(), document) + runCatching { + Files.move( + temp, + target, + StandardCopyOption.REPLACE_EXISTING, + StandardCopyOption.ATOMIC_MOVE + ) + }.onFailure { + Files.move(temp, target, StandardCopyOption.REPLACE_EXISTING) + } + } + + private fun fileOf(id: String): Path = (dir ?: Path.of("data", "layouts")).resolve("$id.json") + + private val LAYOUT_ID = Regex("[A-Za-z0-9_-]{1,64}") + /** * 默认桌面:12 列网格 + 千分比坐标的示例布局。 * diff --git a/ComposeRemoteServer/src/main/resources/application.yml b/ComposeRemoteServer/src/main/resources/application.yml index d2e63c1..3bcdf48 100644 --- a/ComposeRemoteServer/src/main/resources/application.yml +++ b/ComposeRemoteServer/src/main/resources/application.yml @@ -1,6 +1,12 @@ server: port: 8000 +app: + # 布局 JSON 的落盘目录,容器里由 LAYOUT_DIR 指向挂载卷。 + layout-dir: ${LAYOUT_DIR:./data/layouts} + # 页面上传的图片目录,接口 /api/remote-ui/assets/{name} 优先读这里。 + assets-dir: ${ASSETS_DIR:./data/assets} + spring: application: name: ComposeRemoteServer diff --git a/ComposeRemoteServer/src/main/resources/static/editor.html b/ComposeRemoteServer/src/main/resources/static/editor.html new file mode 100644 index 0000000..1a534f4 --- /dev/null +++ b/ComposeRemoteServer/src/main/resources/static/editor.html @@ -0,0 +1,883 @@ + + + + + +Remote UI 布局编辑器 + + + + +

+
Remote UI 布局编辑器desktop
+
+ + + + + +
+
+ +
+
+
+ 拖动组件移动 · 右下角缩放 · 自动吸附网格
+ x / w 吸附 1/12 列,y / h 吸附 5‰,方向键微调,Delete 删除 +
+
+
+
+
+
+
+
+ + +
+ +
+ + + +