feat: 完善后台布局编辑器,新增多页面与图片上传

- 服务端:布局 JSON 持久化与删除接口,页面接口支持 ETag 条件请求与任意布局路由

- 服务端:新增 POST /api/remote-ui/assets 图片上传,文件名带内容哈希,便于客户端缓存

- 编辑器:多页面切换/新建/删除、画布比例自适应、撤销重做、复制粘贴、层级与对齐线

- 编辑器:图片属性面板支持上传图片并自动回填 URL 与像素尺寸

- 客户端:文档磁盘缓存与 If-None-Match 条件请求,304 时复用缓存

- 部署:镜像升级到 1.0.0-editor5,挂载布局与图片目录
This commit is contained in:
tongtong committed 2026-11-25 03:14:52 +08:00
1 parent 07b038b4e7
commit a77293dadd
7 files changed
+847 -107

No files matched your search

@@ -63,10 +63,11 @@ private val client = OkHttpClient.Builder()
.readTimeout(10, TimeUnit.SECONDS)
.build()
/** 一次页面请求的结果:文档字节 + 文档引用的图片地址。 */
/** 一次页面请求的结果:文档字节 + 文档引用的图片地址 + 服务端 ETag。 */
private class RemoteUiPayload(
val bytes: ByteArray,
val assets: List<String>,
val etag: String? = null,
)
/**
@@ -91,6 +92,39 @@ private object RemoteDocumentStore {
fun put(page: String, payload: RemoteUiPayload) {
documents[page] = payload
}
/** 文档与 ETag 落盘,进程重启后仍可发条件请求拿到 304。 */
fun readDisk(context: Context, page: String): RemoteUiPayload? = runCatching {
val name = sha256(page)
val bytes = File(diskDir(context), "$name.bin").takeIf { it.isFile }?.readBytes()
?: return@runCatching null
val meta = File(diskDir(context), "$name.meta").takeIf { it.isFile }?.readLines().orEmpty()
RemoteUiPayload(
bytes = bytes,
assets = meta.drop(1).filter { it.isNotBlank() },
etag = meta.firstOrNull()?.takeIf { it.isNotBlank() },
)
}.getOrNull()
fun writeDisk(context: Context, page: String, payload: RemoteUiPayload) {
runCatching {
val dir = diskDir(context)
val name = sha256(page)
val temp = File(dir, "$name.bin.tmp")
temp.writeBytes(payload.bytes)
if (!temp.renameTo(File(dir, "$name.bin"))) temp.delete()
File(dir, "$name.meta").writeText(
(listOf(payload.etag ?: "") + payload.assets).joinToString("\n")
)
}.onFailure { Log.w("RemoteDocumentStore", "写入文档缓存失败 $page: ${it.message}") }
}
private fun diskDir(context: Context): File =
File(context.cacheDir, "remote-docs").apply { mkdirs() }
private fun sha256(value: String): String =
MessageDigest.getInstance("SHA-256").digest(value.toByteArray())
.joinToString("") { "%02x".format(it.toInt() and 0xFF) }
}
private sealed interface RemoteUiState {
@@ -208,10 +242,20 @@ private class RemoteImageLoader(context: Context) {
}
}
private suspend fun fetchRemoteUi(page: String, baseUrl: String): RemoteUiPayload =
withContext(Dispatchers.IO) {
val request = Request.Builder().url("$baseUrl/api/remote-ui/$page").build()
/**
* 请求页面文档;本地已有 ETag 时发条件请求,304 返回 null 表示沿用缓存。
*/
private suspend fun fetchRemoteUi(
page: String,
baseUrl: String,
cached: RemoteUiPayload?,
): RemoteUiPayload? = withContext(Dispatchers.IO) {
val request = Request.Builder()
.url("$baseUrl/api/remote-ui/$page")
.apply { cached?.etag?.let { header("If-None-Match", it) } }
.build()
client.newCall(request).execute().use { response ->
if (response.code == 304) return@withContext null
if (!response.isSuccessful) {
throw IOException("HTTP ${response.code}")
}
@@ -221,12 +265,12 @@ private suspend fun fetchRemoteUi(page: String, baseUrl: String): RemoteUiPayloa
?.map { it.trim() }
?.filter { it.isNotEmpty() }
.orEmpty()
RemoteUiPayload(bytes, assets)
}
RemoteUiPayload(bytes, assets, response.header("ETag"))
}
}
/**
* 取出页面文档字节:命中缓存就不重复下载。
* 取出页面文档字节:内存 → 磁盘缓存 → 条件请求,服务端 304 时直接复用缓存。
*
* 解析([RemoteDocument] 构造)放在 [Dispatchers.Default],避免大文档阻塞主线程;
* 图片必须在返回前完成预取,否则播放器渲染时会取不到图片。
@@ -235,10 +279,19 @@ private suspend fun loadDocument(
page: String,
baseUrl: String,
imageLoader: RemoteImageLoader,
context: Context,
): RemoteDocument {
val payload = RemoteDocumentStore.get(page) ?: fetchRemoteUi(page, baseUrl).also {
val cached = RemoteDocumentStore.get(page)
?: RemoteDocumentStore.readDisk(context, page)?.also { RemoteDocumentStore.put(page, it) }
val payload = try {
fetchRemoteUi(page, baseUrl, cached)?.also {
RemoteDocumentStore.put(page, it)
}
RemoteDocumentStore.writeDisk(context, page, it)
} ?: cached
} catch (e: IOException) {
// 网络失败时退回本地缓存,保证离线也能看到上一次的页面。
cached ?: throw e
} ?: throw IOException("空响应")
// 文档以 URL 形式声明图片,解析阶段就会校验该开关(默认关闭)。
Limits.ENABLE_IMAGE_URLS = true
val document = withContext(Dispatchers.Default) { RemoteDocument(payload.bytes) }
@@ -405,7 +458,7 @@ fun RemoteUIScreen(
state = RemoteUiState.Loading
}
state = try {
RemoteUiState.Success(loadDocument(page, baseUrl, imageLoader))
RemoteUiState.Success(loadDocument(page, baseUrl, imageLoader, appContext))
} catch (e: Exception) {
Log.e("RemoteUIScreen", "加载页面 $page 失败", e)
RemoteUiState.Error(e.message ?: "加载失败")
+1 -1
View File
@@ -22,7 +22,7 @@ spec:
spec:
containers:
- name: server
image: composeremote/server:1.0.0-editor2
image: composeremote/server:1.0.0-editor5
imagePullPolicy: Never
ports:
- name: http
@@ -1,10 +1,12 @@
package com.ttstd.composeremote.server.controller;
import com.ttstd.composeremote.server.layout.LayoutDocument;
import com.ttstd.composeremote.server.layout.LayoutPages;
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.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
@@ -74,6 +76,18 @@ public class LayoutAdminController {
return ResponseEntity.ok(document);
}
/** 删除布局;默认桌面不允许删除,避免客户端首页无布局可编译。 */
@DeleteMapping("/{id}")
public ResponseEntity<Object> delete(@PathVariable("id") String id) {
if (LayoutPages.DESKTOP.equals(id)) {
return ResponseEntity.badRequest().body(Map.of("error", "默认桌面不能删除"));
}
if (!LayoutStore.INSTANCE.remove(id)) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "布局不存在: " + id);
}
return ResponseEntity.noContent().build();
}
/** 布局摘要。 */
public record LayoutSummary(String id, String title, int items) {
}
@@ -2,6 +2,7 @@ package com.ttstd.composeremote.server.controller;
import com.ttstd.composeremote.server.RemoteDocumentBuilderKt;
import com.ttstd.composeremote.server.layout.LayoutPages;
import com.ttstd.composeremote.server.layout.LayoutStore;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.CacheControl;
@@ -10,16 +11,28 @@ 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.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.server.ResponseStatusException;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import java.util.HexFormat;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
/**
* 服务端驱动 UI 接口。
@@ -39,6 +52,12 @@ import java.util.Locale;
@RequestMapping("/api/remote-ui")
public class RemoteUIController {
/** 上传允许的图片扩展名;webp 服务端无法解析尺寸,暂不支持上传。 */
private static final Set<String> UPLOAD_EXTENSIONS = Set.of("png", "jpg", "jpeg", "gif");
/** 单张图片上限,与 application.yml 的 multipart 限制保持一致。 */
private static final long MAX_ASSET_BYTES = 10L * 1024 * 1024;
/** 图片资源目录,优先于 classpath 里的内置资源;容器中由 ASSETS_DIR 指向挂载卷。 */
@Value("${app.assets-dir:./data/assets}")
private String assetsDir;
@@ -47,9 +66,12 @@ public class RemoteUIController {
value = {"/{page}", ""},
produces = MediaType.APPLICATION_OCTET_STREAM_VALUE
)
public ResponseEntity<byte[]> getPage(@PathVariable(name = "page", required = false) String page) {
public ResponseEntity<byte[]> getPage(
@PathVariable(name = "page", required = false) String page,
@RequestHeader(name = "If-None-Match", required = false) String ifNoneMatch) {
String target = (page == null || page.isBlank()) ? "home" : page;
boolean layoutPage = LayoutPages.DESKTOP.equals(target);
// 存储里存在同名布局时优先走布局编译,便于编辑器新建任意页面。
boolean layoutPage = LayoutStore.INSTANCE.get(target) != null;
byte[] document = layoutPage
? LayoutPages.buildDocument(target)
: RemoteDocumentBuilderKt.buildRemoteDocument(target);
@@ -57,14 +79,35 @@ public class RemoteUIController {
? LayoutPages.assets(target)
: RemoteDocumentBuilderKt.buildRemoteDocumentAssets(target);
// ETag 取文档字节哈希:内容不变时客户端只做一次条件请求,服务端返回 304。
String etag = etagOf(document);
if (etag.equals(ifNoneMatch)) {
return ResponseEntity.status(HttpStatus.NOT_MODIFIED)
.eTag(etag)
.cacheControl(CacheControl.noCache())
.build();
}
ResponseEntity.BodyBuilder builder = ResponseEntity.ok()
.contentType(MediaType.APPLICATION_OCTET_STREAM);
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.eTag(etag)
.cacheControl(CacheControl.noCache());
if (!assets.isEmpty()) {
builder.header("X-Remote-Assets", String.join(",", assets));
}
return builder.body(document);
}
/** 文档字节的短哈希,固定 16 字节(32 位十六进制)作为 ETag。 */
private static String etagOf(byte[] document) {
try {
byte[] hash = MessageDigest.getInstance("SHA-256").digest(document);
return "\"" + HexFormat.of().formatHex(hash, 0, 16) + "\"";
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("SHA-256 不可用", e);
}
}
/**
* 页面引用的图片资源。
*
@@ -90,6 +133,80 @@ public class RemoteUIController {
.body(body);
}
/**
* 编辑器上传图片。
*
* <p>文件落到 {@code app.assets-dir},随后即可通过 {@link #getAsset(String)} 访问。
* 文件名由「安全化的原名 + 内容哈希前 8 位 + 扩展名」组成:同名文件重复上传不会互相覆盖,
* 内容变化时 URL 也随之变化,客户端按 URL 做的图片缓存自然不会读到旧图。
*/
@PostMapping(value = "/assets", consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> uploadAsset(@RequestPart("file") MultipartFile file) {
if (file == null || file.isEmpty()) {
return ResponseEntity.badRequest().body(Map.of("error", "上传文件为空"));
}
String original = file.getOriginalFilename() == null ? "" : file.getOriginalFilename();
String extension = extensionOf(original);
if (!UPLOAD_EXTENSIONS.contains(extension)) {
return ResponseEntity.badRequest().body(Map.of("error", "只支持 png、jpg、gif 图片"));
}
if (file.getSize() > MAX_ASSET_BYTES) {
return ResponseEntity.badRequest().body(Map.of("error", "图片不能超过 10MB"));
}
try {
byte[] bytes = file.getBytes();
BufferedImage image = ImageIO.read(new ByteArrayInputStream(bytes));
if (image == null) {
return ResponseEntity.badRequest().body(Map.of("error", "无法解析图片,请换一张试试"));
}
String name = assetName(original, extension, bytes);
Path directory = Path.of(assetsDir).toAbsolutePath().normalize();
Files.createDirectories(directory);
Files.write(directory.resolve(name), bytes);
return ResponseEntity.ok(Map.of(
"name", name,
"path", "/api/remote-ui/assets/" + name,
"pixelWidth", image.getWidth(),
"pixelHeight", image.getHeight()
));
} catch (IOException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Map.of("error", "图片保存失败: " + e.getMessage()));
}
}
/** 取文件扩展名(小写);没有扩展名时返回空串。 */
private static String extensionOf(String filename) {
int dot = filename.lastIndexOf('.');
if (dot < 0 || dot == filename.length() - 1) {
return "";
}
return filename.substring(dot + 1).toLowerCase(Locale.ROOT);
}
/** 生成安全且内容相关的文件名,例如 {@code lake-landscape-1a2b3c4d.jpg}。 */
private static String assetName(String original, String extension, byte[] bytes) {
String base = original;
int dot = base.lastIndexOf('.');
if (dot >= 0) {
base = base.substring(0, dot);
}
base = base.replaceAll("[^A-Za-z0-9_-]", "-").replaceAll("-{2,}", "-");
if (base.isEmpty()) {
base = "image";
}
if (base.length() > 40) {
base = base.substring(0, 40);
}
try {
byte[] hash = MessageDigest.getInstance("SHA-256").digest(bytes);
return base + "-" + HexFormat.of().formatHex(hash, 0, 4) + "." + extension;
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("SHA-256 不可用", e);
}
}
/** 读取外部图片目录里的文件;不存在或越界时返回 null。 */
private byte[] readExternalAsset(String name) throws IOException {
Path directory = Path.of(assetsDir).toAbsolutePath().normalize();
@@ -57,6 +57,14 @@ object LayoutStore {
fun all(): List<LayoutDocument> = layouts.values.sortedBy { it.id }
/** 删除布局并移除落盘文件;布局不存在时返回 false。 */
fun remove(id: String): Boolean {
if (layouts.remove(id) == null) return false
runCatching { Files.deleteIfExists(fileOf(id)) }
.onFailure { log.warn("布局文件删除失败: {}", fileOf(id), it) }
return true
}
/** 校验并保存布局;校验不通过时抛 [IllegalArgumentException]。 */
fun put(document: LayoutDocument) {
validate(document)
@@ -10,6 +10,11 @@ app:
spring:
application:
name: ComposeRemoteServer
servlet:
multipart:
# 编辑器上传图片的限制:单文件 10MB,整请求放宽到 12MB。
max-file-size: 10MB
max-request-size: 12MB
web:
resources:
cache:
File diff suppressed because it is too large. Load diff