Add image buttons and exclusive launcher actions
This commit is contained in:
1 parent
8d604a5807
commit
74c725e8d7
23 files changed
+871
-107
No files matched your search
@@ -26,7 +26,7 @@ spec:
|
||||
spec:
|
||||
containers:
|
||||
- name: server
|
||||
image: docker.io/library/vibe-launcher-backend:1.1.0-deploy14
|
||||
image: docker.io/library/vibe-launcher-backend:1.1.0-deploy17
|
||||
imagePullPolicy: IfNotPresent
|
||||
ports:
|
||||
- name: http
|
||||
|
||||
@@ -166,6 +166,45 @@ class LayoutController {
|
||||
return serve(store.byRevision(revision));
|
||||
}
|
||||
|
||||
@PostMapping("/api/admin/images")
|
||||
Map<String, String> uploadImage(HttpServletRequest request, HttpServletResponse response)
|
||||
throws SQLException, IOException {
|
||||
policy.requireAdmin(request, response);
|
||||
byte[] bytes = request.getInputStream().readNBytes(512 * 1024 + 1);
|
||||
if (bytes.length > 512 * 1024) throw new ApiError(413, "图片不能超过 512 KiB");
|
||||
String type;
|
||||
try (var stream = new javax.imageio.stream.MemoryCacheImageInputStream(new java.io.ByteArrayInputStream(bytes))) {
|
||||
var readers = javax.imageio.ImageIO.getImageReaders(stream);
|
||||
if (!readers.hasNext()) throw new ApiError(415, "仅支持 PNG 和 JPEG");
|
||||
var reader = readers.next();
|
||||
try {
|
||||
type = switch (reader.getFormatName().toLowerCase(java.util.Locale.ROOT)) {
|
||||
case "png" -> "image/png";
|
||||
case "jpeg" -> "image/jpeg";
|
||||
default -> throw new ApiError(415, "仅支持 PNG 和 JPEG");
|
||||
};
|
||||
reader.setInput(stream);
|
||||
if (reader.getWidth(0) > 1024 || reader.getHeight(0) > 1024) {
|
||||
throw new ApiError(422, "图片宽高不能超过 1024 像素");
|
||||
}
|
||||
reader.read(0);
|
||||
} finally {
|
||||
reader.dispose();
|
||||
}
|
||||
} catch (IOException error) {
|
||||
throw new ApiError(400, "图片文件无法解码");
|
||||
}
|
||||
return Map.of("id", store.saveImage(bytes, type));
|
||||
}
|
||||
|
||||
@GetMapping("/api/images/{id:[a-f0-9]{64}}")
|
||||
ResponseEntity<byte[]> image(@PathVariable String id, HttpServletRequest request, HttpServletResponse response)
|
||||
throws SQLException {
|
||||
policy.requireImageAccess(request, response);
|
||||
var image = store.image(id);
|
||||
return ResponseEntity.ok().contentType(MediaType.parseMediaType(image.mediaType())).body(image.bytes());
|
||||
}
|
||||
|
||||
@PutMapping("/api/admin/layout")
|
||||
ResponseEntity<byte[]> publish(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException {
|
||||
policy.requireAdmin(request, response);
|
||||
|
||||
@@ -25,6 +25,8 @@ class LayoutStore {
|
||||
private static final String LATEST = "SELECT revision, layout FROM releases ORDER BY revision DESC LIMIT 1";
|
||||
private static final String BY_REVISION = "SELECT revision, layout FROM releases WHERE revision = ?";
|
||||
|
||||
record ImageAsset(String mediaType, byte[] bytes) {}
|
||||
|
||||
record Release(int revision, String layout) {
|
||||
String etag() {
|
||||
return "\"" + java.util.HexFormat.of().formatHex(RequestPolicy.sha256(layout)) + "\"";
|
||||
@@ -69,6 +71,11 @@ class LayoutStore {
|
||||
component TEXT PRIMARY KEY
|
||||
) STRICT
|
||||
""");
|
||||
statement.execute("""
|
||||
CREATE TABLE IF NOT EXISTS image_assets (
|
||||
id TEXT PRIMARY KEY, media_type TEXT NOT NULL, bytes BLOB NOT NULL
|
||||
) STRICT
|
||||
""");
|
||||
for (var column : List.of("label", "app_label", "category")) {
|
||||
boolean exists;
|
||||
try (var check = connection.prepareStatement(
|
||||
@@ -141,6 +148,32 @@ class LayoutStore {
|
||||
}
|
||||
}
|
||||
|
||||
String saveImage(byte[] bytes, String mediaType) throws SQLException {
|
||||
String id;
|
||||
try {
|
||||
id = java.util.HexFormat.of().formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes));
|
||||
} catch (java.security.NoSuchAlgorithmException impossible) {
|
||||
throw new IllegalStateException(impossible);
|
||||
}
|
||||
try (var db = connect(); var insert = db.prepareStatement("INSERT OR IGNORE INTO image_assets VALUES (?, ?, ?)")) {
|
||||
insert.setString(1, id);
|
||||
insert.setString(2, mediaType);
|
||||
insert.setBytes(3, bytes);
|
||||
insert.executeUpdate();
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
ImageAsset image(String id) throws SQLException {
|
||||
try (var db = connect(); var query = db.prepareStatement("SELECT media_type, bytes FROM image_assets WHERE id = ?")) {
|
||||
query.setString(1, id);
|
||||
try (var rows = query.executeQuery()) {
|
||||
if (!rows.next()) throw new ApiError(404, "图片资源不存在");
|
||||
return new ImageAsset(rows.getString(1), rows.getBytes(2));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int latestRevision() throws SQLException {
|
||||
try (var connection = connect(); var statement = connection.createStatement();
|
||||
var rows = statement.executeQuery("SELECT MAX(revision) FROM releases")) {
|
||||
@@ -209,6 +242,21 @@ class LayoutStore {
|
||||
throw new ApiError(422, "历史版本布局校验失败,无法回滚", issues.stream().limit(100).toList());
|
||||
}
|
||||
}
|
||||
var imageIds = new java.util.HashSet<String>();
|
||||
for (var page : layout.path("pages")) {
|
||||
for (var item : page.path("items")) {
|
||||
var id = item.path("payload").path("imageId").stringValue("");
|
||||
if (!id.isEmpty()) imageIds.add(id);
|
||||
}
|
||||
}
|
||||
try (var image = connection.prepareStatement("SELECT 1 FROM image_assets WHERE id = ?")) {
|
||||
for (var id : imageIds) {
|
||||
image.setString(1, id);
|
||||
try (var rows = image.executeQuery()) {
|
||||
if (!rows.next()) throw new ApiError(422, "布局引用了未上传的图片");
|
||||
}
|
||||
}
|
||||
}
|
||||
int revision = current.revision() + 1;
|
||||
String json = mapper.writeValueAsString(layout.put("schemaVersion", 3).put("revision", revision));
|
||||
if (json.getBytes(StandardCharsets.UTF_8).length > MAX_BYTES) throw new ApiError(413, "布局超过 1 MiB");
|
||||
|
||||
@@ -14,7 +14,7 @@ class LayoutValidator {
|
||||
record Issue(String level, String path, String message) {}
|
||||
private record Rect(String path, float x, float y, float right, float bottom) {}
|
||||
|
||||
private static final Set<String> TYPES = Set.of("app_icon", "widget", "shortcut", "dock_bg");
|
||||
private static final Set<String> TYPES = Set.of("app_icon", "widget", "shortcut", "dock_bg", "image");
|
||||
private static final Set<String> FIT_MODES = Set.of("contain", "elastic", "stretch");
|
||||
private static final Set<String> BACKGROUNDS = Set.of("wallpaper", "solid", "gradient");
|
||||
private static final Pattern HEX_COLOR = Pattern.compile("#[0-9A-Fa-f]{6}");
|
||||
@@ -23,6 +23,18 @@ class LayoutValidator {
|
||||
private static final int MAX_ID_LENGTH = 64;
|
||||
private static final int MAX_LABEL_LENGTH = 100;
|
||||
|
||||
private static final Set<String> ICON_STYLES = Set.of("original", "system", "circle", "rounded");
|
||||
private static final Set<String> SETTINGS_ACTIONS = Set.of(
|
||||
"ACTION_SETTINGS", "ACTION_WIFI_SETTINGS", "ACTION_BLUETOOTH_SETTINGS", "ACTION_WIRELESS_SETTINGS",
|
||||
"ACTION_AIRPLANE_MODE_SETTINGS", "ACTION_DISPLAY_SETTINGS", "ACTION_SOUND_SETTINGS",
|
||||
"ACTION_LOCATION_SOURCE_SETTINGS", "ACTION_APPLICATION_SETTINGS", "ACTION_DATE_SETTINGS",
|
||||
"ACTION_ACCESSIBILITY_SETTINGS");
|
||||
private static final Pattern CLASS_NAME = Pattern.compile("\\.?[A-Za-z_$][\\w$]*(\\.[A-Za-z_$][\\w$]*)*");
|
||||
private static final Pattern DECIMAL = Pattern.compile("[-+]?(?:[0-9]+(?:\\.[0-9]*)?|\\.[0-9]+)(?:[eE][-+]?[0-9]+)?");
|
||||
private static final Set<String> LAUNCH_MODES = Set.of("none", "settings", "application", "intent", "component");
|
||||
private static final Pattern PACKAGE_NAME = Pattern.compile("[A-Za-z_$][\\w$]*(\\.[A-Za-z_$][\\w$]*)*");
|
||||
private static final Pattern IMAGE_ID = Pattern.compile("[a-f0-9]{64}");
|
||||
|
||||
List<Issue> validate(JsonNode layout) {
|
||||
List<Issue> issues = new ArrayList<>();
|
||||
if (!layout.isObject()) {
|
||||
@@ -36,6 +48,9 @@ class LayoutValidator {
|
||||
error(issues, "revision", "版本号必须是整数");
|
||||
}
|
||||
|
||||
if (!optional(layout, "iconStyle", n -> ICON_STYLES.contains(n.stringValue("")))) {
|
||||
error(issues, "iconStyle", "未知的默认图标样式");
|
||||
}
|
||||
JsonNode canvas = layout.path("canvas");
|
||||
JsonNode fit = layout.path("fit");
|
||||
if (!optional(layout, "canvas", n -> n.isObject() &&
|
||||
@@ -172,11 +187,46 @@ class LayoutValidator {
|
||||
private void validatePayload(List<Issue> issues, JsonNode item, String path, String type) {
|
||||
JsonNode payload = item.path("payload");
|
||||
if (!optional(item, "payload", n -> n.isObject()
|
||||
&& optionalFields(n, LayoutValidator::nullableText, "label", "package", "provider", "intent")
|
||||
&& optionalFields(n, LayoutValidator::nullableText, "label", "package", "provider", "intent", "className", "settingsAction", "launchMode", "componentName")
|
||||
&& optional(n, "radius", value -> value.isNull() || integer(value)))) {
|
||||
error(issues, path + ".payload", "内容字段格式错误");
|
||||
return;
|
||||
}
|
||||
String style = payload.path("iconStyle").stringValue("");
|
||||
if (!optional(payload, "iconStyle", n -> ICON_STYLES.contains(n.stringValue("")) || "image".equals(n.stringValue("")))) {
|
||||
error(issues, path + ".payload.iconStyle", "未知的图标样式");
|
||||
}
|
||||
if (!optional(payload, "imageId", n -> IMAGE_ID.matcher(n.stringValue("")).matches())
|
||||
|| ((type.equals("image") || style.equals("image")) && !payload.hasNonNull("imageId"))) {
|
||||
error(issues, path + ".payload.imageId", "请上传有效的图片");
|
||||
}
|
||||
String mode = payload.path("launchMode").stringValue("");
|
||||
if (payload.has("launchMode") && !LAUNCH_MODES.contains(mode)) {
|
||||
error(issues, path + ".payload.launchMode", "未知的点击动作类型");
|
||||
}
|
||||
String cls = payload.path("className").stringValue("").strip();
|
||||
boolean packageMissing = payload.path("package").stringValue("").isBlank();
|
||||
if ((mode.equals("application") || mode.isEmpty() && !cls.isEmpty())
|
||||
&& (packageMissing || !cls.isEmpty() && !CLASS_NAME.matcher(cls).matches())) {
|
||||
error(issues, path + ".payload.className", "Activity 类名格式无效,或缺少应用包名");
|
||||
}
|
||||
String setting = payload.path("settingsAction").stringValue("");
|
||||
if ((mode.equals("settings") || mode.isEmpty() && !setting.isEmpty()) && !SETTINGS_ACTIONS.contains(setting)) {
|
||||
error(issues, path + ".payload.settingsAction", "请选择有效的系统设置动作");
|
||||
}
|
||||
String component = payload.path("componentName").stringValue("").strip();
|
||||
if (mode.equals("component") || mode.isEmpty() && !component.isEmpty()) {
|
||||
String[] parts = component.split("/", -1);
|
||||
if (parts.length != 2 || !PACKAGE_NAME.matcher(parts[0]).matches() || !CLASS_NAME.matcher(parts[1]).matches()) {
|
||||
error(issues, path + ".payload.componentName", "ComponentName 应为包名/类名");
|
||||
}
|
||||
}
|
||||
if (mode.equals("intent") && payload.path("intent").stringValue("").isBlank()) {
|
||||
error(issues, path + ".payload.intent", "请填写快捷方式 Intent");
|
||||
}
|
||||
if (!optional(payload, "extras", LayoutValidator::validExtras)) {
|
||||
error(issues, path + ".payload.extras", "Intent 参数键重复、为空或值与类型不符");
|
||||
}
|
||||
if (type.equals("app_icon") && payload.path("package").stringValue("").isBlank()) {
|
||||
error(issues, path + ".payload.package", "应用图标需要包名");
|
||||
}
|
||||
@@ -196,6 +246,34 @@ class LayoutValidator {
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean validExtras(JsonNode extras) {
|
||||
if (!extras.isArray() || extras.size() > 32) return false;
|
||||
var keys = new java.util.HashSet<String>();
|
||||
for (var extra : extras) {
|
||||
var key = extra.path("key").stringValue("").strip();
|
||||
var value = extra.path("value").stringValue(null);
|
||||
if (key.isEmpty() || key.length() > 128 || !keys.add(key) || value == null || value.length() > 2048) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
String trimmed = value.strip();
|
||||
switch (extra.path("type").stringValue("")) {
|
||||
case "string" -> { }
|
||||
case "boolean" -> { if (!trimmed.equals("true") && !trimmed.equals("false")) return false; }
|
||||
case "int" -> Integer.parseInt(trimmed);
|
||||
case "long" -> Long.parseLong(trimmed);
|
||||
case "double" -> {
|
||||
if (!DECIMAL.matcher(trimmed).matches() || !Double.isFinite(Double.parseDouble(trimmed))) return false;
|
||||
}
|
||||
default -> { return false; }
|
||||
}
|
||||
} catch (NumberFormatException invalid) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static boolean validCoordinates(JsonNode item) {
|
||||
JsonNode x = item.path("x"), y = item.path("y"), w = item.path("w"), h = item.path("h");
|
||||
return finiteFloat(x) && finiteFloat(y) && finiteFloat(w) && finiteFloat(h)
|
||||
|
||||
@@ -52,6 +52,12 @@ class RequestPolicy extends OncePerRequestFilter {
|
||||
require(request, response, device);
|
||||
}
|
||||
|
||||
void requireImageAccess(HttpServletRequest request, HttpServletResponse response) {
|
||||
String header = request.getHeader("Authorization");
|
||||
if (header != null && MessageDigest.isEqual(sha256(header), device)) return;
|
||||
requireAdmin(request, response);
|
||||
}
|
||||
|
||||
private void require(HttpServletRequest request, HttpServletResponse response, byte[] expected) {
|
||||
String header = request.getHeader("Authorization");
|
||||
if (header == null || !MessageDigest.isEqual(sha256(header), expected)) {
|
||||
|
||||
@@ -34,6 +34,41 @@ class LayoutApiTest {
|
||||
|
||||
@TempDir Path dir;
|
||||
|
||||
@Test
|
||||
void imageUploadCanBePublishedAndFetchedByDevice() throws Exception {
|
||||
Path database = dir.resolve("images.sqlite");
|
||||
MockMvc mvc = mvc(database);
|
||||
var pixels = new java.awt.image.BufferedImage(2, 2, java.awt.image.BufferedImage.TYPE_INT_ARGB);
|
||||
var output = new java.io.ByteArrayOutputStream();
|
||||
javax.imageio.ImageIO.write(pixels, "png", output);
|
||||
byte[] png = output.toByteArray();
|
||||
mvc.perform(post("/api/admin/images").header("Authorization", DEVICE).content(png))
|
||||
.andExpect(status().isUnauthorized());
|
||||
var response = mvc.perform(post("/api/admin/images").header("Authorization", ADMIN)
|
||||
.contentType("image/png").content(png)).andExpect(status().isOk()).andReturn().getResponse();
|
||||
String id = mapper.readTree(response.getContentAsString()).path("id").stringValue();
|
||||
mvc.perform(get("/api/images/" + id)).andExpect(status().isUnauthorized());
|
||||
mvc(database).perform(get("/api/images/" + id).header("Authorization", DEVICE))
|
||||
.andExpect(status().isOk()).andExpect(content().contentTypeCompatibleWith("image/png"))
|
||||
.andExpect(content().bytes(png));
|
||||
|
||||
var current = mvc.perform(get(ADMIN_LAYOUT).header("Authorization", ADMIN))
|
||||
.andReturn().getResponse();
|
||||
String tag = current.getHeader("ETag");
|
||||
var body = """
|
||||
{"iconStyle":"system","pages":[{"items":[
|
||||
{"id":"picture","type":"image","x":12,"y":150,"w":100,"h":100,
|
||||
"payload":{"imageId":"%s","package":"org.example.app"}}
|
||||
]}]}
|
||||
""";
|
||||
mvc.perform(put(ADMIN_LAYOUT).header("Authorization", ADMIN).header("If-Match", tag)
|
||||
.contentType(MediaType.APPLICATION_JSON).content(body.formatted("0".repeat(64))))
|
||||
.andExpect(status().is(422));
|
||||
mvc.perform(put(ADMIN_LAYOUT).header("Authorization", ADMIN).header("If-Match", tag)
|
||||
.contentType(MediaType.APPLICATION_JSON).content(body.formatted(id)))
|
||||
.andExpect(status().isOk());
|
||||
}
|
||||
|
||||
@Test
|
||||
void layoutEventStreamRequiresDeviceToken() throws Exception {
|
||||
MockMvc mvc = mvc(dir.resolve("events.sqlite"));
|
||||
|
||||
@@ -13,6 +13,28 @@ class LayoutValidatorTest {
|
||||
private final LayoutValidator validator = new LayoutValidator();
|
||||
private final JsonMapper mapper = JsonMapper.builder().build();
|
||||
|
||||
@Test
|
||||
void validatesSettingsActionsAndTypedExtras() throws Exception {
|
||||
var json = """
|
||||
{"pages":[{"items":[{"id":"wifi","type":"image","x":0,"y":200,"w":100,"h":100,
|
||||
"payload":{"imageId":"%s","settingsAction":"ACTION_WIFI_SETTINGS",
|
||||
"extras":[{"key":"example","type":"long","value":"9223372036854775807"}]}}]}]}
|
||||
""".formatted("a".repeat(64));
|
||||
var reader = tools.jackson.databind.json.JsonMapper.builder().build();
|
||||
var validator = new LayoutValidator();
|
||||
assertTrue(validator.validate(reader.readTree(json)).stream().noneMatch(i -> i.level().equals("error")));
|
||||
assertTrue(validator.validate(reader.readTree(json.replace("9223372036854775807", "9223372036854775808")))
|
||||
.stream().anyMatch(i -> i.path().endsWith(".extras")));
|
||||
assertTrue(validator.validate(reader.readTree(json.replace("ACTION_WIFI_SETTINGS", "ACTION_CALL")))
|
||||
.stream().anyMatch(i -> i.path().endsWith(".settingsAction")));
|
||||
var component = json.replace("\"settingsAction\":\"ACTION_WIFI_SETTINGS\"", """
|
||||
"launchMode":"component","componentName":"com.example.app/.MainActivity"
|
||||
""".strip());
|
||||
assertTrue(validator.validate(reader.readTree(component)).stream().noneMatch(i -> i.level().equals("error")));
|
||||
assertTrue(validator.validate(reader.readTree(component.replace("/.MainActivity", "")))
|
||||
.stream().anyMatch(i -> i.path().endsWith(".componentName")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void builtInLayoutHasNoErrors() throws Exception {
|
||||
try (var input = new ClassPathResource("launcher/default_layout.json").getInputStream()) {
|
||||
|
||||
Reference in new issue
Block a user