Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

♻️ Complete broadcast API contract migration https://github.com/siyuan-note/siyuan/issues/19378

Daniel45a1eba8ba2c
diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.ts
index 0e2d9ce391..de9a806489 100644
--- a/app/src/types/api/index.d.ts
+++ b/app/src/types/api/index.d.ts
@@ -78,6 +78,22 @@ export type Bookmark = { "blocks": Array<SearchBlock | null> | null; "count": nu
export type BootProgressData = { "details": string; "progress": number; };
+export type BroadcastChannel = { "count": number; "name": string; };
+
+export type BroadcastChannelData = { "channel": BroadcastChannel | null; };
+
+export type BroadcastChannelRequestInput = { "name": string; };
+
+export type BroadcastChannelsData = { "channels": Array<BroadcastChannel | null>; };
+
+export type BroadcastMessageRequestInput = { "channel": string; "message": string; };
+
+export type BroadcastPublishData = { "results": Array<BroadcastPublishResult | null>; };
+
+export type BroadcastPublishMessage = { "filename": string; "size": number; "type": "string" | "binary"; };
+
+export type BroadcastPublishResult = { "channel": BroadcastChannel; "code": number; "message": BroadcastPublishMessage; "msg": string; };
+
export type ChangeMasterPasswordRequestInput = { "newPassword": string; "oldPassword": string; };
export type ChangeSortNotebookRequestInput = { "notebooks": Array<string>; };
@@ -594,10 +610,6 @@ export type APILegacyPOSTPath =
"/api/bazaar/uninstallBazaarTheme" |
"/api/bazaar/uninstallBazaarWidget" |
"/api/bazaar/updateBazaarPackage" |
- "/api/broadcast/getChannelInfo" |
- "/api/broadcast/getChannels" |
- "/api/broadcast/postMessage" |
- "/api/broadcast/publish" |
"/api/clipboard/cleanupRichText" |
"/api/clipboard/prepareRichText" |
"/api/clipboard/readFilePaths" |
@@ -1256,6 +1268,26 @@ export interface APIPOSTRoutes {
response: { "code": 0; "data": null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
body: "json";
};
+ "/api/broadcast/getChannelInfo": {
+ request: BroadcastChannelRequestInput;
+ response: { "code": 0; "data": BroadcastChannelData; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
+ body: "json";
+ };
+ "/api/broadcast/getChannels": {
+ request: EmptyRequestInput;
+ response: { "code": 0; "data": BroadcastChannelsData; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
+ body: "none";
+ };
+ "/api/broadcast/postMessage": {
+ request: BroadcastMessageRequestInput;
+ response: { "code": 0; "data": BroadcastChannelData; "msg": string; } | { "code": -1 | 1; "data": { "closeTimeout": number; } | null; "msg": string; };
+ body: "json";
+ };
+ "/api/broadcast/publish": {
+ request: Record<string, Array<string | Blob>>;
+ response: { "code": 0; "data": BroadcastPublishData; "msg": string; } | { "code": -1 | 1; "data": { "closeTimeout": number; } | null; "msg": string; };
+ body: "multipart";
+ };
"/api/convert/pandoc": {
request: PandocRequestInput;
response: { "code": 0; "data": PandocData; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
diff --git a/app/src/util/contractFormData.test.ts b/app/src/util/contractFormData.test.ts
index dc4c049aa9..6a4fcec840 100644
--- a/app/src/util/contractFormData.test.ts
+++ b/app/src/util/contractFormData.test.ts
@@ -2,6 +2,17 @@ import * as assert from "node:assert/strict";
import {test} from "node:test";
import {ContractFormData} from "./contractFormData";
+test("preserves repeated text and file entries under a dynamic channel name", async () => {
+ const data = new ContractFormData({channel: [" first ", "second", new Blob(["file"])], empty: []});
+ const values = data.getAll("channel");
+ assert.equal(values.length, 3);
+ assert.equal(values[0], " first ");
+ assert.equal(values[1], "second");
+ assert.ok(values[2] instanceof Blob);
+ assert.equal(await values[2].text(), "file");
+ assert.equal(data.has("empty"), false);
+});
+
test("serializes typed upload fields without trimming passwords or adding omitted values", async () => {
const data = new ContractFormData({file: new Blob(["backup"]), password: " secret ", omitted: undefined});
assert.equal(data.get("password"), " secret ");
diff --git a/app/src/util/contractFormData.ts b/app/src/util/contractFormData.ts
index 4445a172ba..035b24945c 100644
--- a/app/src/util/contractFormData.ts
+++ b/app/src/util/contractFormData.ts
@@ -1,14 +1,16 @@
import type {APIFormData} from "../types/api";
// 从类型化字段构造上传表单,保留文件名和可缺省字段。
-export class ContractFormData<Request extends Record<string, string | Blob | undefined>> extends FormData implements APIFormData<Request> {
+export class ContractFormData<Request extends Record<string, string | Blob | Array<string | Blob> | undefined>> extends FormData implements APIFormData<Request> {
public readonly apiRequest: Request;
constructor(request: Request) {
super();
this.apiRequest = request;
Object.entries(request).forEach(([name, value]) => {
- if (value !== undefined) {
+ if (Array.isArray(value)) {
+ value.forEach(item => this.append(name, item));
+ } else if (value !== undefined) {
this.append(name, value);
}
});
diff --git a/docs/API-CONTRACTS.md b/docs/API-CONTRACTS.md
index bbea2c6fbb..4688c01cae 100644
--- a/docs/API-CONTRACTS.md
+++ b/docs/API-CONTRACTS.md
@@ -60,6 +60,8 @@ Frontend callers construct `ContractFormData` from typed fields before passing i
## Endpoint maintenance
+Dynamic multipart endpoints use `MultipartFields` to retain every text value and file under each field name. Its request schema maps field names to arrays of text or binary values; `ContractFormData` appends each array item as a repeated form field. This is distinct from fixed-field uploads, which continue to bind the first value. Broadcast publication preserves text-before-file processing and its per-message error results. Endpoint-specific `DecodeFailure` handling preserves existing parsing error codes and payloads.
+
1. Define or update transport types and endpoints in the contract package, specifying request bodies, error codes, null values, defaults, and historical input compatibility
2. Bind business entry points through `contractHandler`, preserving route middleware order, authorization, and lease scope
3. Routes with type contracts must not also appear in `legacy_routes.json`; remove records for deleted endpoints, and never add new endpoints to the list
diff --git a/docs/API-CONTRACTS.zh-CN.md b/docs/API-CONTRACTS.zh-CN.md
index f857687f51..ec35a4d045 100644
--- a/docs/API-CONTRACTS.zh-CN.md
+++ b/docs/API-CONTRACTS.zh-CN.md
@@ -60,6 +60,8 @@
## 接口维护流程
+动态上传接口使用 `MultipartFields` 保留每个字段名对应的全部文本值和文件。请求模式将字段名映射为文本或二进制值的数组,`ContractFormData` 将数组中的每一项追加为同名表单字段。固定字段上传仍绑定首个值。广播发布保留先处理文本、再处理文件的顺序及逐条消息的错误结果。端点专用的 `DecodeFailure` 处理保留原有解析错误码和载荷。
+
1. 在契约包中定义或更新传输类型与端点,明确请求体、错误码、空值、默认值和历史输入兼容规则
2. 用 `contractHandler` 绑定业务入口,保持路由中间件顺序、授权和租约范围
3. 使用类型契约的路由不得同时出现在 `legacy_routes.json`;删除接口时同步移除对应记录,新增接口不得加入该清单
diff --git a/kernel/api/broadcast.go b/kernel/api/broadcast.go
index d7c594ef28..e7e4e13221 100644
--- a/kernel/api/broadcast.go
+++ b/kernel/api/broadcast.go
@@ -22,12 +22,12 @@ import (
"sync"
"time"
- "github.com/88250/gulu"
"github.com/asaskevich/EventBus"
"github.com/gin-contrib/sse"
"github.com/gin-gonic/gin"
"github.com/olahol/melody"
"github.com/siyuan-note/logging"
+ "github.com/siyuan-note/siyuan/kernel/apicontract"
"github.com/siyuan-note/siyuan/kernel/util"
)
@@ -346,20 +346,6 @@ type ChannelInfo struct {
Count int `json:"count"`
}
-type PublishMessage struct {
- Type MessageType `json:"type"` // "string" | "binary"
- Size int `json:"size"` // message size
- Filename string `json:"filename"` // empty string for string-message
-}
-
-type PublishResult struct {
- Code int `json:"code"` // 0: success
- Msg string `json:"msg"` // error message
-
- Channel ChannelInfo `json:"channel"`
- Message PublishMessage `json:"message"`
-}
-
// broadcast create a broadcast channel WebSocket connection
//
// @param
@@ -577,23 +563,11 @@ func broadcastSubscribe(c *gin.Context) {
// }[],
// },
// }
-func broadcastPublish(c *gin.Context) {
- ret := gulu.Ret.NewResult()
- defer c.JSON(http.StatusOK, ret)
-
- results := []*PublishResult{}
-
- // Multipart form
- form, err := c.MultipartForm()
- if err != nil {
- ret.Code = 1
- ret.Msg = err.Error()
- return
- }
-
+var broadcastPublish = contractHandler(apicontract.BroadcastPublish, func(c *gin.Context, request apicontract.MultipartFields) apicontract.Response[apicontract.BroadcastPublishData] {
+ results := []*apicontract.BroadcastPublishResult{}
// Broadcast string messages
- for name, values := range form.Value {
- channel := ChannelInfo{
+ for name, values := range request.Value {
+ channel := apicontract.BroadcastChannel{
Name: name,
Count: 0,
}
@@ -608,12 +582,12 @@ func broadcastPublish(c *gin.Context) {
// Broadcast each string message to the same channel
for _, value := range values {
- result := &PublishResult{
+ result := &apicontract.BroadcastPublishResult{
Code: 0,
Msg: "",
Channel: channel,
- Message: PublishMessage{
- Type: MessageTypeString,
+ Message: apicontract.BroadcastPublishMessage{
+ Type: string(MessageTypeString),
Size: len(value),
Filename: "",
},
@@ -633,8 +607,8 @@ func broadcastPublish(c *gin.Context) {
}
// Broadcast binary message
- for name, files := range form.File {
- channel := ChannelInfo{
+ for name, files := range request.File {
+ channel := apicontract.BroadcastChannel{
Name: name,
Count: 0,
}
@@ -649,12 +623,12 @@ func broadcastPublish(c *gin.Context) {
// Broadcast each binary message to the same channel
for _, file := range files {
- result := &PublishResult{
+ result := &apicontract.BroadcastPublishResult{
Code: 0,
Msg: "",
Channel: channel,
- Message: PublishMessage{
- Type: MessageTypeBinary,
+ Message: apicontract.BroadcastPublishMessage{
+ Type: string(MessageTypeBinary),
Size: int(file.Size),
Filename: file.Filename,
},
@@ -688,10 +662,8 @@ func broadcastPublish(c *gin.Context) {
}
}
- ret.Data = map[string]any{
- "results": results,
- }
-}
+ return apicontract.Success(apicontract.BroadcastPublishData{Results: results})
+})
// postMessage send string message to a broadcast channel
//
@@ -714,24 +686,10 @@ func broadcastPublish(c *gin.Context) {
// },
// },
// }
-func postMessage(c *gin.Context) {
- ret := gulu.Ret.NewResult()
- defer c.JSON(http.StatusOK, ret)
+var postMessage = contractHandler(apicontract.PostBroadcastMessage, func(c *gin.Context, request apicontract.BroadcastMessageRequest) apicontract.Response[apicontract.BroadcastChannelData] {
- arg, ok := util.JsonArg(c, ret)
- if !ok {
- return
- }
-
- var message, channelName string
- if !util.ParseJsonArgs(arg, ret,
- util.BindJsonArg("message", &message, true, true),
- util.BindJsonArg("channel", &channelName, true, true),
- ) {
- return
- }
-
- channel := &ChannelInfo{
+ message, channelName := request.Message, request.Channel
+ channel := &apicontract.BroadcastChannel{
Name: channelName,
Count: 0,
}
@@ -744,15 +702,11 @@ func postMessage(c *gin.Context) {
if _, err := broadcastChannel.BroadcastString(message); err != nil {
logging.LogErrorf("broadcast message failed: %s", err)
- ret.Code = 1
- ret.Msg = err.Error()
- return
+ return apicontract.Failure[apicontract.BroadcastChannelData](1, err.Error())
}
}
- ret.Data = map[string]any{
- "channel": channel,
- }
-}
+ return apicontract.Success(apicontract.BroadcastChannelData{Channel: channel})
+})
// getChannelInfo gets the information of a broadcast channel
//
@@ -774,21 +728,10 @@ func postMessage(c *gin.Context) {
// },
// },
// }
-func getChannelInfo(c *gin.Context) {
- ret := gulu.Ret.NewResult()
- defer c.JSON(http.StatusOK, ret)
-
- arg, ok := util.JsonArg(c, ret)
- if !ok {
- return
- }
+var getChannelInfo = contractHandler(apicontract.GetBroadcastChannelInfo, func(c *gin.Context, request apicontract.BroadcastChannelRequest) apicontract.Response[apicontract.BroadcastChannelData] {
- var name string
- if !util.ParseJsonArgs(arg, ret, util.BindJsonArg("name", &name, true, true)) {
- return
- }
-
- channel := &ChannelInfo{
+ name := request.Name
+ channel := &apicontract.BroadcastChannel{
Name: name,
Count: 0,
}
@@ -800,10 +743,8 @@ func getChannelInfo(c *gin.Context) {
channel.Count = broadcastChannel.SubscriberCount()
}
- ret.Data = map[string]any{
- "channel": channel,
- }
-}
+ return apicontract.Success(apicontract.BroadcastChannelData{Channel: channel})
+})
// getChannels gets the channel name and lintener number of all broadcast chanel
//
@@ -819,20 +760,16 @@ func getChannelInfo(c *gin.Context) {
// }[],
// },
// }
-func getChannels(c *gin.Context) {
- ret := gulu.Ret.NewResult()
- defer c.JSON(http.StatusOK, ret)
+var getChannels = contractHandler(apicontract.GetBroadcastChannels, func(c *gin.Context, request apicontract.EmptyRequest) apicontract.Response[apicontract.BroadcastChannelsData] {
- channels := []*ChannelInfo{}
+ channels := []*apicontract.BroadcastChannel{}
BroadcastChannels.Range(func(key, value any) bool {
broadcastChannel := value.(*BroadcastChannel)
- channels = append(channels, &ChannelInfo{
+ channels = append(channels, &apicontract.BroadcastChannel{
Name: key.(string),
Count: broadcastChannel.SubscriberCount(),
})
return true
})
- ret.Data = map[string]any{
- "channels": channels,
- }
-}
+ return apicontract.Success(apicontract.BroadcastChannelsData{Channels: channels})
+})
diff --git a/kernel/api/contract_broadcast_test.go b/kernel/api/contract_broadcast_test.go
new file mode 100644
index 0000000000..de76722462
--- /dev/null
+++ b/kernel/api/contract_broadcast_test.go
@@ -0,0 +1,96 @@
+package api
+
+import (
+ "bytes"
+ "encoding/json"
+ "github.com/gin-gonic/gin"
+ "github.com/siyuan-note/siyuan/kernel/apicontract"
+ "mime/multipart"
+ "net/http/httptest"
+ "strings"
+ "testing"
+)
+
+func TestAPIContractBroadcastMultipart(t *testing.T) {
+ var body bytes.Buffer
+ writer := multipart.NewWriter(&body)
+ for _, text := range []string{" first ", "second"} {
+ if err := writer.WriteField("contract-multipart", text); err != nil {
+ t.Fatal(err)
+ }
+ }
+ for _, name := range []string{"first.txt", "second.txt"} {
+ file, err := writer.CreateFormFile("contract-multipart", name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = file.Write([]byte("abc")); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := writer.Close(); err != nil {
+ t.Fatal(err)
+ }
+ engine := gin.New()
+ engine.POST("/api/broadcast/publish", broadcastPublish)
+ recorder := httptest.NewRecorder()
+ request := httptest.NewRequest("POST", "/api/broadcast/publish", &body)
+ request.Header.Set("Content-Type", writer.FormDataContentType())
+ engine.ServeHTTP(recorder, request)
+ requireAPIContract(t, "POST", "/api/broadcast/publish", recorder)
+ var response struct {
+ Code int `json:"code"`
+ Data apicontract.BroadcastPublishData `json:"data"`
+ }
+ if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil {
+ t.Fatal(err)
+ }
+ if response.Code != 0 || len(response.Data.Results) != 4 {
+ t.Fatalf("lost multipart entries: %s", recorder.Body.String())
+ }
+ for i, result := range response.Data.Results {
+ if result.Channel.Name != "contract-multipart" || result.Code != 0 {
+ t.Fatalf("invalid result: %#v", result)
+ }
+ if i < 2 && (result.Message.Type != "string" || result.Message.Size != []int{7, 6}[i]) {
+ t.Fatalf("text changed: %#v", result.Message)
+ }
+ if i >= 2 && (result.Message.Type != "binary" || result.Message.Size != 3 || result.Message.Filename != []string{"first.txt", "second.txt"}[i-2]) {
+ t.Fatalf("file changed: %#v", result.Message)
+ }
+ }
+ recorder = httptest.NewRecorder()
+ engine.ServeHTTP(recorder, httptest.NewRequest("POST", "/api/broadcast/publish", strings.NewReader("invalid")))
+ requireAPIContract(t, "POST", "/api/broadcast/publish", recorder)
+ if !strings.Contains(recorder.Body.String(), `"code":1`) {
+ t.Fatalf("multipart error code changed: %s", recorder.Body.String())
+ }
+}
+
+func TestAPIContractBroadcastChannels(t *testing.T) {
+ engine := gin.New()
+ engine.POST("/api/broadcast/getChannelInfo", getChannelInfo)
+ engine.POST("/api/broadcast/getChannels", getChannels)
+ engine.POST("/api/broadcast/postMessage", postMessage)
+ for _, entry := range []struct{ path, body string }{
+ {"/api/broadcast/getChannelInfo", `{"name":" contract-absent "}`},
+ {"/api/broadcast/postMessage", `{"channel":" contract-absent ","message":" hello "}`},
+ {"/api/broadcast/getChannels", `{`},
+ } {
+ recorder := httptest.NewRecorder()
+ engine.ServeHTTP(recorder, httptest.NewRequest("POST", entry.path, strings.NewReader(entry.body)))
+ requireAPIContract(t, "POST", entry.path, recorder)
+ var response struct {
+ Code int `json:"code"`
+ Data struct {
+ Channel *ChannelInfo `json:"channel"`
+ } `json:"data"`
+ }
+ if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil || response.Code != 0 {
+ t.Fatalf("unexpected channel response: %s, %v", recorder.Body.String(), err)
+ }
+ if entry.path != "/api/broadcast/getChannels" && (response.Data.Channel == nil || response.Data.Channel.Name != "contract-absent" || response.Data.Channel.Count != 0) {
+ t.Fatalf("channel changed: %s", recorder.Body.String())
+ }
+ }
+}
diff --git a/kernel/apicontract/broadcast.go b/kernel/apicontract/broadcast.go
new file mode 100644
index 0000000000..9902644d32
--- /dev/null
+++ b/kernel/apicontract/broadcast.go
@@ -0,0 +1,46 @@
+package apicontract
+
+type BroadcastMessageRequest struct {
+ Message string `json:"message" api:"trim"`
+ Channel string `json:"channel" api:"trim"`
+}
+
+type BroadcastChannelRequest struct {
+ Name string `json:"name" api:"trim"`
+}
+
+type BroadcastChannel struct {
+ Name string `json:"name"`
+ Count int `json:"count"`
+}
+
+type BroadcastChannelData struct {
+ Channel *BroadcastChannel `json:"channel"`
+}
+
+type BroadcastChannelsData struct {
+ Channels []*BroadcastChannel `json:"channels" api:"nonnullable"`
+}
+
+type BroadcastPublishMessage struct {
+ Type string `json:"type" api:"enum=string|binary"`
+ Size int `json:"size"`
+ Filename string `json:"filename"`
+}
+
+type BroadcastPublishResult struct {
+ Code int `json:"code"`
+ Msg string `json:"msg"`
+ Channel BroadcastChannel `json:"channel"`
+ Message BroadcastPublishMessage `json:"message"`
+}
+
+type BroadcastPublishData struct {
+ Results []*BroadcastPublishResult `json:"results" api:"nonnullable"`
+}
+
+func init() {
+ BroadcastPublish.decodeFailure = func(err error) Response[BroadcastPublishData] {
+ return Failure[BroadcastPublishData](1, err.Error())
+ }
+}
diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.go
index eba0d77e6c..f3d432677b 100644
--- a/kernel/apicontract/contracts.go
+++ b/kernel/apicontract/contracts.go
@@ -427,3 +427,11 @@ var SetPetalEnabled = define[SetPetalEnabledRequest, *Petal]("setPetalEnabled",
var SetPetalPublishEnabled = define[SetPetalPublishEnabledRequest, *Petal]("setPetalPublishEnabled", "/api/petal/setPetalPublishEnabled", JSONBody, ResponseOptions{}, "POST")
var Pandoc = define[PandocRequest, PandocData]("pandoc", "/api/convert/pandoc", JSONBody, ResponseOptions{}, "POST")
+
+var PostBroadcastMessage = define[BroadcastMessageRequest, BroadcastChannelData]("postMessage", "/api/broadcast/postMessage", JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")
+
+var GetBroadcastChannelInfo = define[BroadcastChannelRequest, BroadcastChannelData]("getChannelInfo", "/api/broadcast/getChannelInfo", JSONBody, ResponseOptions{}, "POST")
+
+var GetBroadcastChannels = define[EmptyRequest, BroadcastChannelsData]("getChannels", "/api/broadcast/getChannels", NoBody, ResponseOptions{}, "POST")
+
+var BroadcastPublish = define[MultipartFields, BroadcastPublishData]("broadcastPublish", "/api/broadcast/publish", MultipartBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")
diff --git a/kernel/apicontract/legacy_routes.json b/kernel/apicontract/legacy_routes.json
index cea4f86ebe..0cf8b3e4f6 100644
--- a/kernel/apicontract/legacy_routes.json
+++ b/kernel/apicontract/legacy_routes.json
@@ -155,10 +155,6 @@
{"method":"POST","path":"/api/bazaar/uninstallBazaarTheme","handler":"uninstallBazaarTheme"},
{"method":"POST","path":"/api/bazaar/uninstallBazaarWidget","handler":"uninstallBazaarWidget"},
{"method":"POST","path":"/api/bazaar/updateBazaarPackage","handler":"updateBazaarPackage"},
- {"method":"POST","path":"/api/broadcast/getChannelInfo","handler":"getChannelInfo"},
- {"method":"POST","path":"/api/broadcast/getChannels","handler":"getChannels"},
- {"method":"POST","path":"/api/broadcast/postMessage","handler":"postMessage"},
- {"method":"POST","path":"/api/broadcast/publish","handler":"broadcastPublish"},
{"method":"POST","path":"/api/clipboard/cleanupRichText","handler":"cleanupRichText"},
{"method":"POST","path":"/api/clipboard/prepareRichText","handler":"prepareRichText"},
{"method":"POST","path":"/api/clipboard/readFilePaths","handler":"readFilePaths"},
diff --git a/kernel/apicontract/multipart.go b/kernel/apicontract/multipart.go
index 7f7563f999..22b7f47b0f 100644
--- a/kernel/apicontract/multipart.go
+++ b/kernel/apicontract/multipart.go
@@ -7,7 +7,16 @@ import (
"strings"
)
+// MultipartFields 按字段名保留全部文本值和文件,同名字段不会合并或截断。
+type MultipartFields struct {
+ Value map[string][]string
+ File map[string][]*multipart.FileHeader
+}
+
func validateMultipartRequest(t reflect.Type) error {
+ if t == reflect.TypeFor[MultipartFields]() {
+ return nil
+ }
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
if !field.IsExported() || field.Anonymous || field.Tag.Get("json") == "" {
@@ -34,6 +43,10 @@ func (e Endpoint[Request, Data]) DecodeMultipart(form *multipart.Form) (request
return request, fmt.Errorf("multipart form is missing")
}
value := reflect.ValueOf(&request).Elem()
+ if value.Type() == reflect.TypeFor[MultipartFields]() {
+ value.Set(reflect.ValueOf(MultipartFields{Value: form.Value, File: form.File}))
+ return
+ }
if value.Kind() != reflect.Struct {
return request, fmt.Errorf("multipart request must be a struct")
}
diff --git a/kernel/apicontract/schema.go b/kernel/apicontract/schema.go
index b169abdf98..3445d38923 100644
--- a/kernel/apicontract/schema.go
+++ b/kernel/apicontract/schema.go
@@ -72,6 +72,12 @@ func nonnullable(schema *Schema) *Schema {
}
func (b *schemaBuilder) schema(t reflect.Type, input bool) (*Schema, error) {
+ if t == reflect.TypeFor[MultipartFields]() {
+ if !input {
+ return nil, fmt.Errorf("multipart fields can only appear in requests")
+ }
+ return &Schema{Type: "object", AdditionalProperties: &Schema{Type: "array", Items: &Schema{AnyOf: []*Schema{{Type: "string"}, {Type: "string", Format: "binary"}}}}}, nil
+ }
if t == reflect.TypeFor[HTMLClipboardData]() {
preflight, err := b.schema(reflect.TypeFor[HTMLClipboardPreflight](), input)
if err != nil {
diff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.json
index ea132f655e..cd5840322b 100644
--- a/kernel/apicontract/schema.json
+++ b/kernel/apicontract/schema.json
@@ -1258,6 +1258,161 @@
],
"additionalProperties": false
},
+ "BroadcastChannel": {
+ "type": "object",
+ "properties": {
+ "count": {
+ "type": "integer"
+ },
+ "name": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "count",
+ "name"
+ ],
+ "additionalProperties": false
+ },
+ "BroadcastChannelData": {
+ "type": "object",
+ "properties": {
+ "channel": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/BroadcastChannel"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ }
+ },
+ "required": [
+ "channel"
+ ],
+ "additionalProperties": false
+ },
+ "BroadcastChannelRequestInput": {
+ "type": "object",
+ "properties": {
+ "name": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "name"
+ ],
+ "additionalProperties": false
+ },
+ "BroadcastChannelsData": {
+ "type": "object",
+ "properties": {
+ "channels": {
+ "type": "array",
+ "items": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/BroadcastChannel"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ }
+ }
+ },
+ "required": [
+ "channels"
+ ],
+ "additionalProperties": false
+ },
+ "BroadcastMessageRequestInput": {
+ "type": "object",
+ "properties": {
+ "channel": {
+ "type": "string"
+ },
+ "message": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "channel",
+ "message"
+ ],
+ "additionalProperties": false
+ },
+ "BroadcastPublishData": {
+ "type": "object",
+ "properties": {
+ "results": {
+ "type": "array",
+ "items": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/BroadcastPublishResult"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ }
+ }
+ },
+ "required": [
+ "results"
+ ],
+ "additionalProperties": false
+ },
+ "BroadcastPublishMessage": {
+ "type": "object",
+ "properties": {
+ "filename": {
+ "type": "string"
+ },
+ "size": {
+ "type": "integer"
+ },
+ "type": {
+ "type": "string",
+ "enum": [
+ "string",
+ "binary"
+ ]
+ }
+ },
+ "required": [
+ "filename",
+ "size",
+ "type"
+ ],
+ "additionalProperties": false
+ },
+ "BroadcastPublishResult": {
+ "type": "object",
+ "properties": {
+ "channel": {
+ "$ref": "#/$defs/BroadcastChannel"
+ },
+ "code": {
+ "type": "integer"
+ },
+ "message": {
+ "$ref": "#/$defs/BroadcastPublishMessage"
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "channel",
+ "code",
+ "message",
+ "msg"
+ ],
+ "additionalProperties": false
+ },
"ChangeMasterPasswordRequestInput": {
"type": "object",
"properties": {
@@ -13371,6 +13526,322 @@
]
}
},
+ {
+ "method": "POST",
+ "path": "/api/broadcast/getChannelInfo",
+ "handler": "getChannelInfo",
+ "body": "json",
+ "request": {
+ "$ref": "#/$defs/BroadcastChannelRequestInput"
+ },
+ "response": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ 0
+ ]
+ },
+ "data": {
+ "$ref": "#/$defs/BroadcastChannelData"
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ -1
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "closeTimeout": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "closeTimeout"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": true
+ }
+ ]
+ }
+ },
+ {
+ "method": "POST",
+ "path": "/api/broadcast/getChannels",
+ "handler": "getChannels",
+ "body": "none",
+ "request": {
+ "$ref": "#/$defs/EmptyRequestInput"
+ },
+ "response": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ 0
+ ]
+ },
+ "data": {
+ "$ref": "#/$defs/BroadcastChannelsData"
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ -1
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "closeTimeout": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "closeTimeout"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": true
+ }
+ ]
+ }
+ },
+ {
+ "method": "POST",
+ "path": "/api/broadcast/postMessage",
+ "handler": "postMessage",
+ "body": "json",
+ "request": {
+ "$ref": "#/$defs/BroadcastMessageRequestInput"
+ },
+ "response": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ 0
+ ]
+ },
+ "data": {
+ "$ref": "#/$defs/BroadcastChannelData"
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ -1,
+ 1
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "closeTimeout": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "closeTimeout"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": true
+ }
+ ]
+ }
+ },
+ {
+ "method": "POST",
+ "path": "/api/broadcast/publish",
+ "handler": "broadcastPublish",
+ "body": "multipart",
+ "request": {
+ "type": "object",
+ "additionalProperties": {
+ "type": "array",
+ "items": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "string",
+ "format": "binary"
+ }
+ ]
+ }
+ }
+ },
+ "response": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ 0
+ ]
+ },
+ "data": {
+ "$ref": "#/$defs/BroadcastPublishData"
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ -1,
+ 1
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "closeTimeout": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "closeTimeout"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": true
+ }
+ ]
+ }
+ },
{
"method": "POST",
"path": "/api/convert/pandoc",