An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:sparkles: Support configuring plugin availability in the publishing service https://github.com/siyuan-note/siyuan/issues/16600
Daniel9f4deeffa57e
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.jsonindex ca46e7f9cf..5d717c77a1 100644--- a/app/appearance/langs/ar.json+++ b/app/appearance/langs/ar.json@@ -1,4 +1,5 @@{+ "pluginDisabledInPublishTip": "عطّل مؤلف الإضافة هذه الإضافة في خدمة النشر","aiMcpEnv": "متغيرات البيئة","aiMcpEnvTip": "تُمرر الأسرار المشار إليها إلى هذا البرنامج، وتُخزن القيم المدخلة مباشرة كنص عادي","aiMcpEnvInvalid": "متغيرات البيئة غير صالحة؛ تحقق من الأسماء الفارغة أو المكررة أو غير الصالحة",diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.jsonindex da135dbdb7..e7e3868462 100644--- a/app/appearance/langs/de.json+++ b/app/appearance/langs/de.json@@ -1,4 +1,5 @@{+ "pluginDisabledInPublishTip": "Der Plugin-Autor hat dieses Plugin im Veröffentlichungsdienst deaktiviert","aiMcpEnv": "Umgebungsvariablen","aiMcpEnvTip": "Referenzierte Geheimnisse werden diesem Programm bereitgestellt, direkt eingegebene Werte werden im Klartext gespeichert","aiMcpEnvInvalid": "Ungültige Umgebungsvariablen; prüfen Sie auf leere, doppelte oder ungültige Namen",diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.jsonindex d54cf8cdc2..c739a1920b 100644--- a/app/appearance/langs/en.json+++ b/app/appearance/langs/en.json@@ -1,4 +1,5 @@{+ "pluginDisabledInPublishTip": "The plugin author has disabled this plugin in the publish service","aiMcpEnv": "Environment variables","aiMcpEnvTip": "Referenced secrets are provided to this program, and direct values are stored in plaintext","aiMcpEnvInvalid": "Invalid environment variables; check for empty, duplicate, or invalid names",diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.jsonindex f1fa6a038d..6dc8dbe4b9 100644--- a/app/appearance/langs/es.json+++ b/app/appearance/langs/es.json@@ -1,4 +1,5 @@{+ "pluginDisabledInPublishTip": "El autor del complemento ha deshabilitado este complemento en el servicio de publicación","aiMcpEnv": "Variables de entorno","aiMcpEnvTip": "Los secretos referenciados se proporcionan a este programa y los valores directos se almacenan como texto sin formato","aiMcpEnvInvalid": "Variables de entorno no válidas; compruebe si hay nombres vacíos, duplicados o no válidos",diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.jsonindex 627ff106ca..77cb7ea1cc 100644--- a/app/appearance/langs/fr.json+++ b/app/appearance/langs/fr.json@@ -1,4 +1,5 @@{+ "pluginDisabledInPublishTip": "L’auteur du plugin a désactivé ce plugin dans le service de publication","aiMcpEnv": "Variables d'environnement","aiMcpEnvTip": "Les secrets référencés sont fournis à ce programme et les valeurs saisies directement sont stockées en texte brut","aiMcpEnvInvalid": "Variables d'environnement non valides ; vérifiez les noms vides, dupliqués ou non valides",diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.jsonindex ffe96555e5..6475e23ac6 100644--- a/app/appearance/langs/he.json+++ b/app/appearance/langs/he.json@@ -1,4 +1,5 @@{+ "pluginDisabledInPublishTip": "מחבר התוסף השבית תוסף זה בשירות הפרסום","aiMcpEnv": "משתני סביבה","aiMcpEnvTip": "סודות שמופנים יועברו לתוכנית זו, וערכים שיוזנו ישירות יישמרו כטקסט גלוי","aiMcpEnvInvalid": "משתני הסביבה אינם תקינים; יש לבדוק שמות ריקים, כפולים או לא תקינים",diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.jsonindex b70859be74..866d60c200 100644--- a/app/appearance/langs/hi.json+++ b/app/appearance/langs/hi.json@@ -1,4 +1,5 @@{+ "pluginDisabledInPublishTip": "प्लगइन लेखक ने इस प्लगइन को प्रकाशन सेवा में अक्षम किया है","aiMcpEnv": "पर्यावरण चर","aiMcpEnvTip": "संदर्भित रहस्य इस प्रोग्राम को दिए जाते हैं और सीधे दर्ज किए गए मान सादे पाठ में संग्रहीत होते हैं","aiMcpEnvInvalid": "पर्यावरण चर अमान्य हैं; खाली, डुप्लिकेट या अमान्य नामों की जाँच करें",diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.jsonindex 0be56b2a7a..973bf2e607 100644--- a/app/appearance/langs/id.json+++ b/app/appearance/langs/id.json@@ -1,4 +1,5 @@{+ "pluginDisabledInPublishTip": "Pembuat plugin telah menonaktifkan plugin ini di layanan penerbitan","aiMcpEnv": "Variabel lingkungan","aiMcpEnvTip": "Rahasia yang dirujuk diberikan kepada program ini dan nilai yang dimasukkan langsung disimpan sebagai teks biasa","aiMcpEnvInvalid": "Variabel lingkungan tidak valid; periksa nama yang kosong, duplikat, atau tidak valid",diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.jsonindex ed9910cd91..3e1cc45d53 100644--- a/app/appearance/langs/it.json+++ b/app/appearance/langs/it.json@@ -1,4 +1,5 @@{+ "pluginDisabledInPublishTip": "L'autore del plugin ha disabilitato questo plugin nel servizio di pubblicazione","aiMcpEnv": "Variabili d'ambiente","aiMcpEnvTip": "I segreti referenziati vengono forniti a questo programma e i valori inseriti direttamente vengono archiviati in testo semplice","aiMcpEnvInvalid": "Variabili d'ambiente non valide; verifica la presenza di nomi vuoti, duplicati o non validi",diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.jsonindex 342d99b106..6ded993fe2 100644--- a/app/appearance/langs/ja.json+++ b/app/appearance/langs/ja.json@@ -1,4 +1,5 @@{+ "pluginDisabledInPublishTip": "プラグインの作者が公開サービスでこのプラグインを無効にしています","aiMcpEnv": "環境変数","aiMcpEnvTip": "参照したシークレットはこのプログラムに渡され、直接入力した値は平文で保存されます","aiMcpEnvInvalid": "環境変数が無効です。名前が空、重複、または無効な文字を含んでいないか確認してください",diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.jsonindex 1c92740249..1675222528 100644--- a/app/appearance/langs/ko.json+++ b/app/appearance/langs/ko.json@@ -1,4 +1,5 @@{+ "pluginDisabledInPublishTip": "플러그인 작성자가 게시 서비스에서 이 플러그인을 비활성화했습니다","aiMcpEnv": "환경 변수","aiMcpEnvTip": "참조된 비밀은 이 프로그램에 제공되며 직접 입력한 값은 일반 텍스트로 저장됩니다","aiMcpEnvInvalid": "환경 변수가 잘못되었습니다. 비어 있거나 중복되거나 잘못된 이름이 있는지 확인하세요",diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.jsonindex 8410a4d7f5..3a36c90e79 100644--- a/app/appearance/langs/nl.json+++ b/app/appearance/langs/nl.json@@ -1,4 +1,5 @@{+ "pluginDisabledInPublishTip": "De auteur van de plug-in heeft deze plug-in uitgeschakeld in de publicatieservice","aiMcpEnv": "Omgevingsvariabelen","aiMcpEnvTip": "Geheimen waarnaar wordt verwezen worden aan dit programma verstrekt en rechtstreeks ingevoerde waarden worden als platte tekst opgeslagen","aiMcpEnvInvalid": "Ongeldige omgevingsvariabelen; controleer op lege, dubbele of ongeldige namen",diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.jsonindex 2b9908084f..0822d1fd53 100644--- a/app/appearance/langs/pl.json+++ b/app/appearance/langs/pl.json@@ -1,4 +1,5 @@{+ "pluginDisabledInPublishTip": "Autor wtyczki wyłączył tę wtyczkę w usłudze publikowania","aiMcpEnv": "Zmienne środowiskowe","aiMcpEnvTip": "Wskazane sekrety są udostępniane temu programowi, a wartości wpisane bezpośrednio są przechowywane jako zwykły tekst","aiMcpEnvInvalid": "Nieprawidłowe zmienne środowiskowe; sprawdź puste, zduplikowane lub nieprawidłowe nazwy",diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.jsonindex 6c20ff1e0d..17133e0e24 100644--- a/app/appearance/langs/pt-BR.json+++ b/app/appearance/langs/pt-BR.json@@ -1,4 +1,5 @@{+ "pluginDisabledInPublishTip": "O autor do plugin desativou este plugin no serviço de publicação","aiMcpEnv": "Variáveis de ambiente","aiMcpEnvTip": "Os segredos referenciados são fornecidos a este programa e os valores inseridos diretamente são armazenados como texto simples","aiMcpEnvInvalid": "Variáveis de ambiente inválidas; verifique se há nomes vazios, duplicados ou inválidos",diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.jsonindex 4330ba4eb8..2c210636c7 100644--- a/app/appearance/langs/ru.json+++ b/app/appearance/langs/ru.json@@ -1,4 +1,5 @@{+ "pluginDisabledInPublishTip": "Автор плагина отключил этот плагин в службе публикации","aiMcpEnv": "Переменные окружения","aiMcpEnvTip": "Указанные секреты передаются этой программе, а введённые напрямую значения хранятся в открытом виде","aiMcpEnvInvalid": "Недопустимые переменные окружения; проверьте пустые, повторяющиеся или недопустимые имена",diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.jsonindex e9925a9c1d..e93ce0c143 100644--- a/app/appearance/langs/sk.json+++ b/app/appearance/langs/sk.json@@ -1,4 +1,5 @@{+ "pluginDisabledInPublishTip": "Autor doplnku zakázal tento doplnok v publikačnej službe","aiMcpEnv": "Premenné prostredia","aiMcpEnvTip": "Odkazované tajomstvá sa poskytnú tomuto programu a priamo zadané hodnoty sa uložia ako obyčajný text","aiMcpEnvInvalid": "Neplatné premenné prostredia; skontrolujte prázdne, duplicitné alebo neplatné názvy",diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.jsonindex 4f458a054b..cb7307ce44 100644--- a/app/appearance/langs/th.json+++ b/app/appearance/langs/th.json@@ -1,4 +1,5 @@{+ "pluginDisabledInPublishTip": "ผู้เขียนปลั๊กอินได้ปิดใช้งานปลั๊กอินนี้ในบริการเผยแพร่","aiMcpEnv": "ตัวแปรสภาพแวดล้อม","aiMcpEnvTip": "ข้อมูลลับที่อ้างอิงจะถูกส่งให้โปรแกรมนี้ และค่าที่ป้อนโดยตรงจะถูกจัดเก็บเป็นข้อความธรรมดา","aiMcpEnvInvalid": "ตัวแปรสภาพแวดล้อมไม่ถูกต้อง โปรดตรวจสอบชื่อที่ว่าง ซ้ำ หรือไม่ถูกต้อง",diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.jsonindex 369e97ece6..229afe8fd4 100644--- a/app/appearance/langs/tr.json+++ b/app/appearance/langs/tr.json@@ -1,4 +1,5 @@{+ "pluginDisabledInPublishTip": "Eklenti yazarı bu eklentiyi yayımlama hizmetinde devre dışı bıraktı","aiMcpEnv": "Ortam değişkenleri","aiMcpEnvTip": "Başvurulan gizli bilgiler bu programa sağlanır ve doğrudan girilen değerler düz metin olarak saklanır","aiMcpEnvInvalid": "Geçersiz ortam değişkenleri; boş, yinelenen veya geçersiz adları kontrol edin",diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.jsonindex 7afc03a4d9..58206a4017 100644--- a/app/appearance/langs/uk.json+++ b/app/appearance/langs/uk.json@@ -1,4 +1,5 @@{+ "pluginDisabledInPublishTip": "Автор плагіна вимкнув цей плагін у службі публікації","aiMcpEnv": "Змінні середовища","aiMcpEnvTip": "Указані секрети передаються цій програмі, а введені безпосередньо значення зберігаються як звичайний текст","aiMcpEnvInvalid": "Недопустимі змінні середовища; перевірте порожні, повторювані або недопустимі назви",diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.jsonindex 9034402aa7..8d094b0c60 100644--- a/app/appearance/langs/zh-CN.json+++ b/app/appearance/langs/zh-CN.json@@ -1,4 +1,5 @@{+ "pluginDisabledInPublishTip": "插件作者已禁止该插件在发布服务中运行","aiMcpEnv": "环境变量","aiMcpEnvTip": "引用的密钥会提供给该程序,直接填写的值将以明文存储","aiMcpEnvInvalid": "环境变量无效,请检查名称是否为空、重复或包含非法字符",diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.jsonindex dd2babde6a..af72af3f7e 100644--- a/app/appearance/langs/zh-TW.json+++ b/app/appearance/langs/zh-TW.json@@ -1,4 +1,5 @@{+ "pluginDisabledInPublishTip": "插件作者已禁止該插件在發布服務中執行","aiMcpEnv": "環境變數","aiMcpEnvTip": "引用的金鑰會提供給該程式,直接填寫的值將以明文儲存","aiMcpEnvInvalid": "環境變數無效,請檢查名稱是否為空、重複或包含無效字元",diff --git a/app/src/config/bazaar.ts b/app/src/config/bazaar.tsindex 1a7b1c9a4a..3427a52305 100644--- a/app/src/config/bazaar.ts+++ b/app/src/config/bazaar.ts@@ -27,6 +27,7 @@ import {getBazaarKernelSystemLabels,getBazaarPackageInvalidLanguageKey,getBazaarThemeModeLabels,+ isBazaarPluginEnabledInPublish,} from "../util/bazaarPackage";/** 集市 Tab 侧栏 / 全局搜索索引文案 */@@ -687,6 +688,8 @@ ${primaryAction ? '<div class="fn__hr"></div>' : ""}// @ts-ignorehasSetting = plugin && (plugin.setting || plugin.__proto__.hasOwnProperty("openSetting"));}+ const showPublishSwitch = bazaarType === "plugins" && window.siyuan.config.publish.enable;+ const publishEnabled = isBazaarPluginEnabledInPublish(bazaarItem);const available = bazaar._getUpdatedItem(bazaarType, bazaarItem.name)?.available;return `<div data-name="${escapeAttr(bazaarItem.name)}" data-package-type="${bazaarType}" data-package-source="downloaded" class="b3-card${bazaarItem.current ? " b3-card--current" : ""}"><div class="b3-card__img"><img src="${bazaarItem.iconURL}" loading="lazy" onerror="this.src='/stage/images/icon.png'"/></div>@@ -694,6 +697,12 @@ ${primaryAction ? '<div class="fn__hr"></div>' : ""}<div class="b3-card__info b3-card__info--left fn__flex-1">${escapeHtml(bazaarItem.preferredName)}<div class="b3-card__desc" title="${escapeAttr(bazaarItem.preferredDesc)}">${escapeHtml(bazaarItem.preferredDesc)}</div>+ ${showPublishSwitch ? `<div class="fn__hr--b"></div>+ <label data-type="plugin-publish-enable-label" class="fn__flex" title="${escapeAttr(bazaarItem.disabledInPublish ? window.siyuan.languages.pluginDisabledInPublishTip : window.siyuan.languages.publishService)}">+ <input data-type="plugin-publish-enable" data-position="north" class="b3-switch fn__flex-center" type="checkbox"${publishEnabled ? " checked" : ""}${bazaarItem.disabledInPublish ? " disabled" : ""}>+ <span class="fn__space--small"></span>+ <span class="fn__flex-center ft__on-surface">${window.siyuan.languages.publishService}</span>+ </label>` : ""}</div></div><div class="b3-card__actions b3-card__actions--right">@@ -1157,6 +1166,20 @@ type="checkbox">loadPlugin(app, response.data).then(callback);});},+ _setPluginPublishEnabled(item: IBazaarItem, enabled: boolean, callback: () => void) {+ fetchPost("/api/petal/setPetalPublishEnabled", {+ packageName: item.name,+ enabled,+ }, response => {+ if (response.code !== 0) {+ showMessage(response.msg);+ callback();+ return;+ }+ item.userDisabledInPublish = !enabled;+ callback();+ });+ },_resolveThemeAppearanceMode(item: IBazaarItem) {const appearance = window.siyuan.config.appearance;const modes = item.modes || [];@@ -1732,6 +1755,20 @@ type="checkbox">}event.stopPropagation();break;+ } else if (type === "plugin-publish-enable-label") {+ event.stopPropagation();+ break;+ } else if (type === "plugin-publish-enable" && installedItem) {+ if (!target.hasAttribute("disabled")) {+ target.setAttribute("disabled", "disabled");+ const enabled = (target as HTMLInputElement).checked;+ bazaar._setPluginPublishEnabled(installedItem, enabled, () => {+ target.removeAttribute("disabled");+ this._genMyHTML("plugins", app, true);+ });+ }+ event.stopPropagation();+ break;} else if (type === "plugin-enable" && (installedItem || pkgItem)) {if (!target.hasAttribute("disabled")) {target.setAttribute("disabled", "disabled");diff --git a/app/src/types/index.d.ts b/app/src/types/index.d.tsindex 088b7567a0..5b786a1184 100644--- a/app/src/types/index.d.ts+++ b/app/src/types/index.d.ts@@ -1065,6 +1065,7 @@ interface IBazaarItem {installedIncompatible?: boolean; // 仅插件/主题bazaarIncompatible?: boolean; // 仅插件/主题enabled?: boolean; // 仅 plugin+ userDisabledInPublish?: boolean; // 仅 pluginmodes?: string[]; // 仅 theme}diff --git a/app/src/util/bazaarPackage.test.ts b/app/src/util/bazaarPackage.test.tsindex fe0ed742f0..257a1872ce 100644--- a/app/src/util/bazaarPackage.test.ts+++ b/app/src/util/bazaarPackage.test.ts@@ -8,6 +8,7 @@ import {getBazaarKernelSystemLabels,getBazaarPackageInvalidLanguageKey,getBazaarThemeModeLabels,+ isBazaarPluginEnabledInPublish,isValidBazaarPackageName,} from "./bazaarPackage";@@ -68,6 +69,18 @@ describe("getBazaarCompatibilityFieldVisibility", () => {});});+describe("isBazaarPluginEnabledInPublish", () => {+ it("requires both the plugin author and the user to allow publishing", () => {+ assert.equal(isBazaarPluginEnabledInPublish({}), true);+ assert.equal(isBazaarPluginEnabledInPublish({disabledInPublish: true}), false);+ assert.equal(isBazaarPluginEnabledInPublish({userDisabledInPublish: true}), false);+ assert.equal(isBazaarPluginEnabledInPublish({+ disabledInPublish: true,+ userDisabledInPublish: true,+ }), false);+ });+});+describe("bazaar system labels", () => {it("treats missing backends as all systems", () => {assert.deepEqual(getBazaarBackendSystemLabels([], "All"), ["All"]);diff --git a/app/src/util/bazaarPackage.ts b/app/src/util/bazaarPackage.tsindex 39685c60c0..a6f45c7467 100644--- a/app/src/util/bazaarPackage.ts+++ b/app/src/util/bazaarPackage.ts@@ -23,6 +23,11 @@ export const getBazaarCompatibilityFieldVisibility = (packageType: string) => {};};+export const isBazaarPluginEnabledInPublish = (item: {+ disabledInPublish?: boolean;+ userDisabledInPublish?: boolean;+}) => !item.disabledInPublish && !item.userDisabledInPublish;+export const getBazaarPackageInvalidLanguageKey = (reason?: TBazaarPackageInvalidReason) => {switch (reason) {case "missing-manifest":diff --git a/app/src/util/processMessage.ts b/app/src/util/processMessage.tsindex 00bfd4c696..9db901d49b 100644--- a/app/src/util/processMessage.ts+++ b/app/src/util/processMessage.ts@@ -62,6 +62,12 @@ export const processMessage = (response: IWebSocketData) => {}return false;}+ if ("reloadpublishpage" === response.cmd) {+ if (window.siyuan.isPublish) {+ window.location.reload();+ }+ return false;+ }if ("closepublishpage" === response.cmd) {handlePublishServiceClosed(response.msg);return false;diff --git a/kernel/api/petal.go b/kernel/api/petal.goindex 87bac2d04f..cfd2589f11 100644--- a/kernel/api/petal.go+++ b/kernel/api/petal.go@@ -79,3 +79,32 @@ func setPetalEnabled(c *gin.Context) {model.PushReloadPlugin(nil, unloadPluginSet, nil, nil, app)}}++func setPetalPublishEnabled(c *gin.Context) {+ ret := gulu.Ret.NewResult()+ defer c.JSON(http.StatusOK, ret)++ arg, ok := util.JsonArg(c, ret)+ if !ok {+ return+ }++ var packageName string+ var enabled bool+ if !util.ParseJsonArgs(arg, ret,+ util.BindJsonArg("packageName", &packageName, true, true),+ util.BindJsonArg("enabled", &enabled, true, false),+ ) {+ return+ }++ data, err := model.SetPetalPublishEnabled(packageName, enabled)+ if err != nil {+ ret.Code = -1+ ret.Msg = err.Error()+ return+ }++ ret.Data = data+ util.ReloadPublishServiceSessions()+}diff --git a/kernel/api/petal_test.go b/kernel/api/petal_test.gonew file mode 100644index 0000000000..a60f6dbd15--- /dev/null+++ b/kernel/api/petal_test.go@@ -0,0 +1,97 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package api++import (+ "bytes"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "testing"++ "github.com/gin-gonic/gin"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/model"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestSetPetalPublishEnabledAuthorization(t *testing.T) {+ gin.SetMode(gin.TestMode)+ originalConf := model.Conf+ originalDataDir := util.DataDir+ model.Conf = model.NewAppConf()+ model.Conf.Bazaar = &conf.Bazaar{Trust: true}+ util.DataDir = t.TempDir()+ t.Cleanup(func() {+ model.Conf = originalConf+ util.DataDir = originalDataDir+ })++ pluginDir := filepath.Join(util.DataDir, "plugins", "example")+ if err := os.MkdirAll(pluginDir, 0755); err != nil {+ t.Fatal(err)+ }+ manifest := []byte(`{"name":"example","version":"1.0.0","minAppVersion":"0.0.1"}`)+ for fileName, content := range map[string][]byte{+ "plugin.json": manifest,+ "index.js": []byte("example"),+ } {+ if err := os.WriteFile(filepath.Join(pluginDir, fileName), content, 0644); err != nil {+ t.Fatal(err)+ }+ }+ if _, err := model.SetPetalEnabled("example", true); err != nil {+ t.Fatal(err)+ }++ body, err := json.Marshal(map[string]any{"packageName": "example", "enabled": false})+ if err != nil {+ t.Fatal(err)+ }+ for _, test := range []struct {+ name string+ role model.Role+ statusCode int+ }{+ {name: "administrator", role: model.RoleAdministrator, statusCode: http.StatusOK},+ {name: "editor", role: model.RoleEditor, statusCode: http.StatusForbidden},+ {name: "reader", role: model.RoleReader, statusCode: http.StatusForbidden},+ } {+ t.Run(test.name, func(t *testing.T) {+ engine := gin.New()+ engine.Use(func(c *gin.Context) {+ c.Set(model.RoleContextKey, test.role)+ c.Next()+ })+ ServeAPI(engine)++ recorder := httptest.NewRecorder()+ request := httptest.NewRequest(http.MethodPost, "/api/petal/setPetalPublishEnabled", bytes.NewReader(body))+ request.Header.Set("Content-Type", "application/json")+ engine.ServeHTTP(recorder, request)+ if recorder.Code != test.statusCode {+ t.Fatalf("unexpected status code: got %d, want %d", recorder.Code, test.statusCode)+ }+ })+ }++ if petal := model.GetPetalByName("example"); petal == nil || !petal.UserDisabledInPublish {+ t.Fatal("administrator publish preference was not persisted")+ }+}diff --git a/kernel/api/router.go b/kernel/api/router.goindex 89dc10a767..b3f775016c 100644--- a/kernel/api/router.go+++ b/kernel/api/router.go@@ -636,6 +636,7 @@ func ServeAPI(ginServer *gin.Engine) {ginServer.Handle("POST", "/api/petal/loadPetals", model.CheckAuth, loadPetals)ginServer.Handle("POST", "/api/petal/setPetalEnabled", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setPetalEnabled)+ ginServer.Handle("POST", "/api/petal/setPetalPublishEnabled", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setPetalPublishEnabled)ginServer.Handle("GET", "/api/plugin/rpc", model.CheckAuth, getLoadedPlugin)ginServer.Handle("GET", "/api/plugin/rpc/:name", model.CheckAuth, getLoadedPlugin)diff --git a/kernel/bazaar/package.go b/kernel/bazaar/package.goindex 40750cd55d..2b40730731 100644--- a/kernel/bazaar/package.go+++ b/kernel/bazaar/package.go@@ -91,6 +91,7 @@ type Package struct {InstalledIncompatible *bool `json:"installedIncompatible,omitempty"` // 插件/主题:本地已安装版本是否不兼容BazaarIncompatible *bool `json:"bazaarIncompatible,omitempty"` // 插件/主题:在线集市版本是否不兼容Enabled *bool `json:"enabled,omitempty"` // Plugin:是否启用+ UserDisabledInPublish *bool `json:"userDisabledInPublish,omitempty"` // Plugin:是否由用户在发布服务中禁用Modes *[]string `json:"modes,omitempty"` // Theme:支持的模式列表}diff --git a/kernel/model/bazaar.go b/kernel/model/bazaar.goindex d9982d85d2..cab0e5131f 100644--- a/kernel/model/bazaar.go+++ b/kernel/model/bazaar.go@@ -409,6 +409,7 @@ func getInstalledPackages0(pkgType, frontend, keyword string) (installedPackagespetal := getPetalByName(pkg.Name, petals)if nil != petal {pkg.Enabled = new(petal.Enabled)+ pkg.UserDisabledInPublish = new(petal.UserDisabledInPublish)}case "themes":pkg.InstalledIncompatible = new(bazaar.IsIncompatibleTheme(pkg, frontend))diff --git a/kernel/model/plugin.go b/kernel/model/plugin.goindex e69d370e67..df388fd8d0 100644--- a/kernel/model/plugin.go+++ b/kernel/model/plugin.go@@ -34,13 +34,14 @@ import (// Petal represents a plugin's management status.type Petal struct {- Name string `json:"name"` // Plugin name- DisplayName string `json:"displayName"` // Plugin display name- Version string `json:"version"` // Plugin version- Enabled bool `json:"enabled"` // Whether enabled- Incompatible bool `json:"incompatible"` // Whether incompatible- DisabledInPublish bool `json:"disabledInPublish"` // Whether disabled in publish mode- DisallowInstall bool `json:"disallowInstall"` // Whether disallow install+ Name string `json:"name"` // Plugin name+ DisplayName string `json:"displayName"` // Plugin display name+ Version string `json:"version"` // Plugin version+ Enabled bool `json:"enabled"` // Whether enabled+ Incompatible bool `json:"incompatible"` // Whether incompatible+ DisabledInPublish bool `json:"disabledInPublish"` // Whether disabled in publish mode+ UserDisabledInPublish bool `json:"userDisabledInPublish"` // 是否由用户在发布服务中禁用+ DisallowInstall bool `json:"disallowInstall"` // Whether disallow installJS string `json:"js"` // JS codeCSS string `json:"css"` // CSS code@@ -62,8 +63,6 @@ var ()func SetPetalEnabled(name string, enabled bool) (ret *Petal, err error) {- petals := getPetals()-found, version, displayName, incompatible, disabledInPublish, disallowInstall, kernelIncompatible := bazaar.ParseInstalledPlugin(name, "")if !found {err = fmt.Errorf("plugin [%s] not found", name)@@ -71,31 +70,27 @@ func SetPetalEnabled(name string, enabled bool) (ret *Petal, err error) {return}- ret = getPetalByName(name, petals)- if nil == ret {- ret = &Petal{- Name: name,+ ret, err = updatePetal(name, func(petal *Petal) error {+ petal.Version = version+ petal.DisplayName = displayName+ petal.Enabled = enabled+ petal.Incompatible = incompatible+ petal.DisabledInPublish = disabledInPublish+ petal.DisallowInstall = disallowInstall+ petal.Kernel = KernelPetal{+ Incompatible: kernelIncompatible,}- petals = append(petals, ret)- }- ret.Version = version- ret.DisplayName = displayName- ret.Enabled = enabled- ret.Incompatible = incompatible- ret.DisabledInPublish = disabledInPublish- ret.DisallowInstall = disallowInstall- ret.Kernel = KernelPetal{- Incompatible: kernelIncompatible,- }- if enabled && disallowInstall {- err = fmt.Errorf("require upgrade SiYuan to use this plugin [%s]", name)+ if enabled && disallowInstall {+ return fmt.Errorf("require upgrade SiYuan to use this plugin [%s]", name)+ }+ return nil+ })+ if err != nil {logging.LogInfof("%s", err)return}- savePetals(petals)-loadCode(ret)// Hook kernel plugin lifecycle (callbacks avoid circular import with plugin package)@@ -111,6 +106,44 @@ func SetPetalEnabled(name string, enabled bool) (ret *Petal, err error) {return}+func SetPetalPublishEnabled(name string, enabled bool) (ret *Petal, err error) {+ found, version, displayName, incompatible, disabledInPublish, disallowInstall, kernelIncompatible := bazaar.ParseInstalledPlugin(name, "")+ if !found {+ err = fmt.Errorf("plugin [%s] not found", name)+ logging.LogErrorf("%s", err)+ return+ }++ ret, err = updatePetal(name, func(petal *Petal) error {+ petal.Version = version+ petal.DisplayName = displayName+ petal.Incompatible = incompatible+ petal.DisabledInPublish = disabledInPublish+ petal.UserDisabledInPublish = !enabled+ petal.DisallowInstall = disallowInstall+ petal.Kernel.Incompatible = kernelIncompatible+ return nil+ })+ return+}++func updatePetal(name string, update func(petal *Petal) error) (ret *Petal, err error) {+ petalsStoreLock.Lock()+ defer petalsStoreLock.Unlock()++ petals := getPetals0()+ ret = getPetalByName(name, petals)+ if ret == nil {+ ret = &Petal{Name: name}+ petals = append(petals, ret)+ }+ if err = update(ret); err != nil {+ return+ }+ savePetals0(petals)+ return+}+func getPetalByName(name string, petals []*Petal) (ret *Petal) {for _, p := range petals {if name == p.Name {@@ -200,11 +233,6 @@ func loadPetals(frontend string, isPublish, isKernel bool) (ret []*Petal) {// incompatible client plugincontinue}-- if isPublish && petal.DisabledInPublish {- // disabled plugin in publish mode- continue- }}if petal.DisallowInstall {@@ -213,6 +241,9 @@ func loadPetals(frontend string, isPublish, isKernel bool) (ret []*Petal) {logging.LogInfof("plugin [%s] disallowed install, auto disabled", petal.Name)continue}+ if isPublish && !isPetalAccessableInPublish(petal, disabledInPublish, disallowInstall) {+ continue+ }loadCode(petal)if isKernel {@@ -353,7 +384,10 @@ func savePetals0(petals []*Petal) {func getPetals() (ret []*Petal) {petalsStoreLock.Lock()defer petalsStoreLock.Unlock()+ return getPetals0()+}+func getPetals0() (ret []*Petal) {ret = []*Petal{}petalDir := filepath.Join(util.DataDir, "storage", "petal")if err := os.MkdirAll(petalDir, 0755); err != nil {diff --git a/kernel/model/plugin_test.go b/kernel/model/plugin_test.goindex 0460418f96..f06bf4addb 100644--- a/kernel/model/plugin_test.go+++ b/kernel/model/plugin_test.go@@ -17,12 +17,84 @@package modelimport (+ "os"+ "path/filepath""testing""github.com/siyuan-note/siyuan/kernel/conf""github.com/siyuan-note/siyuan/kernel/util")+func TestSetPetalPublishEnabled(t *testing.T) {+ originalConf := Conf+ originalDataDir := util.DataDir+ Conf = NewAppConf()+ Conf.Bazaar = &conf.Bazaar{Trust: true}+ util.DataDir = t.TempDir()+ t.Cleanup(func() {+ Conf = originalConf+ util.DataDir = originalDataDir+ })++ pluginDir := filepath.Join(util.DataDir, "plugins", "example")+ if err := os.MkdirAll(pluginDir, 0755); err != nil {+ t.Fatal(err)+ }+ manifest := []byte(`{"name":"example","version":"1.0.0","minAppVersion":"0.0.1","disabledInPublish":false,"kernels":["all"]}`)+ if err := os.WriteFile(filepath.Join(pluginDir, "plugin.json"), manifest, 0644); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(pluginDir, "index.js"), []byte("export default class {}"), 0644); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(pluginDir, "kernel.js"), []byte("export const onload = () => {}"), 0644); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(pluginDir, "README.md"), []byte("example"), 0644); err != nil {+ t.Fatal(err)+ }++ if _, err := SetPetalEnabled("example", true); err != nil {+ t.Fatal(err)+ }+ if petal := GetPetalByName("example"); petal == nil || petal.UserDisabledInPublish {+ t.Fatal("plugin should be enabled in publish by default")+ }++ if _, err := SetPetalPublishEnabled("example", false); err != nil {+ t.Fatal(err)+ }+ if petal := GetPetalByName("example"); petal == nil || !petal.UserDisabledInPublish {+ t.Fatal("plugin publish preference was not persisted")+ }+ packages := GetInstalledPackages("plugins", "", "")+ if len(packages) != 1 || packages[0].UserDisabledInPublish == nil || !*packages[0].UserDisabledInPublish {+ t.Fatal("installed plugin data should include the user publish preference")+ }+ if petals := LoadPetals("", false); len(petals) != 1 || petals[0].Name != "example" {+ t.Fatal("user publish preference should not disable the plugin outside publish")+ }+ if petals := LoadPetals("", true); len(petals) != 0 {+ t.Fatal("user-disabled plugin should not load in publish")+ }+ if petals := LoadKernelPetals(); len(petals) != 1 || petals[0].Name != "example" {+ t.Fatal("user publish preference should not disable the kernel plugin")+ }++ if _, err := SetPetalEnabled("example", false); err != nil {+ t.Fatal(err)+ }+ if petal := GetPetalByName("example"); petal == nil || !petal.UserDisabledInPublish {+ t.Fatal("normal plugin state changes should preserve the publish preference")+ }+ if _, err := SetPetalPublishEnabled("example", true); err != nil {+ t.Fatal(err)+ }+ if petal := GetPetalByName("example"); petal == nil || petal.UserDisabledInPublish {+ t.Fatal("plugin publish preference was not enabled")+ }+}+func TestIsPetalsEnabled(t *testing.T) {originalConf := ConforiginalContainer := util.Containerdiff --git a/kernel/model/publish_resource_access.go b/kernel/model/publish_resource_access.goindex 8435f042d3..9a3c9f7afc 100644--- a/kernel/model/publish_resource_access.go+++ b/kernel/model/publish_resource_access.go@@ -66,7 +66,11 @@ func CheckPluginAccessableInPublish(name string) bool {}found, _, _, _, disabledInPublish, disallowInstall, _ := bazaar.ParseInstalledPlugin(name, "")- return found && !disabledInPublish && !disallowInstall+ return found && isPetalAccessableInPublish(petal, disabledInPublish, disallowInstall)+}++func isPetalAccessableInPublish(petal *Petal, disabledInPublish, disallowInstall bool) bool {+ return petal != nil && petal.Enabled && !petal.UserDisabledInPublish && !disabledInPublish && !disallowInstall}func CheckWidgetAccessableInPublish(name string) bool {diff --git a/kernel/model/publish_resource_access_test.go b/kernel/model/publish_resource_access_test.goindex d9810b4ba3..6d331fcc4a 100644--- a/kernel/model/publish_resource_access_test.go+++ b/kernel/model/publish_resource_access_test.go@@ -124,6 +124,7 @@ func TestCheckPluginAccessableInPublish(t *testing.T) {}writePlugin("allowed", false)writePlugin("publish-disabled", true)+ writePlugin("user-disabled", false)writePlugin("disabled", false)if err := os.MkdirAll(filepath.Join(util.DataDir, "storage", "petal"), 0755); err != nil {t.Fatal(err)@@ -131,6 +132,7 @@ func TestCheckPluginAccessableInPublish(t *testing.T) {savePetals([]*Petal{{Name: "allowed", Enabled: true},{Name: "publish-disabled", Enabled: true},+ {Name: "user-disabled", Enabled: true, UserDisabledInPublish: true},{Name: "disabled", Enabled: false},})@@ -140,6 +142,9 @@ func TestCheckPluginAccessableInPublish(t *testing.T) {if CheckPluginAccessableInPublish("publish-disabled") {t.Fatal("publish-disabled plugin should not be accessable")}+ if CheckPluginAccessableInPublish("user-disabled") {+ t.Fatal("user-disabled plugin should not be accessable")+ }if CheckPluginAccessableInPublish("disabled") {t.Fatal("disabled plugin should not be accessable")}diff --git a/kernel/model/push_reload.go b/kernel/model/push_reload.goindex 42089e0204..5669561a13 100644--- a/kernel/model/push_reload.go+++ b/kernel/model/push_reload.go@@ -83,6 +83,9 @@ func PushReloadPlugin(uninstallPluginNameSet, unloadPluginNameSet, reloadPluginS"reloadPlugins": slices[2], // 插件启用,或插件代码变更"dataChangePlugins": slices[3], // 插件存储数据变更}+ if 0 < len(slices[0])+len(slices[1])+len(slices[2]) {+ util.ReloadPublishServiceSessions()+ }if "" == excludeApp {util.BroadcastByType("main", "reloadPlugin", 0, "", payload)diff --git a/kernel/server/serve_static_test.go b/kernel/server/serve_static_test.goindex a83e036273..cb276f584f 100644--- a/kernel/server/serve_static_test.go+++ b/kernel/server/serve_static_test.go@@ -191,3 +191,63 @@ func TestSnippetPublishAccess(t *testing.T) {t.Fatalf("unexpected administrator fallback response: status=%d body=%q", recorder.Code, recorder.Body.String())}}++func TestPluginPublishAccess(t *testing.T) {+ gin.SetMode(gin.TestMode)+ originalDataDir := util.DataDir+ originalConf := model.Conf+ util.DataDir = t.TempDir()+ model.Conf = model.NewAppConf()+ model.Conf.Bazaar = &conf.Bazaar{Trust: true}+ t.Cleanup(func() {+ util.DataDir = originalDataDir+ model.Conf = originalConf+ })++ writePlugin := func(name string) {+ pluginDir := filepath.Join(util.DataDir, "plugins", name)+ if err := os.MkdirAll(pluginDir, 0755); err != nil {+ t.Fatal(err)+ }+ manifest := []byte(`{"name":"` + name + `","version":"1.0.0","minAppVersion":"0.0.1"}`)+ for fileName, content := range map[string][]byte{+ "plugin.json": manifest,+ "index.js": []byte(name),+ } {+ if err := os.WriteFile(filepath.Join(pluginDir, fileName), content, 0644); err != nil {+ t.Fatal(err)+ }+ }+ if _, err := model.SetPetalEnabled(name, true); err != nil {+ t.Fatal(err)+ }+ }+ writePlugin("allowed")+ writePlugin("user-disabled")+ if _, err := model.SetPetalPublishEnabled("user-disabled", false); err != nil {+ t.Fatal(err)+ }++ request := func(role model.Role, requestPath string) *httptest.ResponseRecorder {+ engine := gin.New()+ engine.Use(func(c *gin.Context) {+ c.Set(model.RoleContextKey, role)+ c.Next()+ })+ servePlugins(engine)+ recorder := httptest.NewRecorder()+ engine.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, requestPath, nil))+ return recorder+ }+ if recorder := request(model.RoleReader, "/plugins/allowed/index.js"); recorder.Code != http.StatusOK ||+ recorder.Body.String() != "allowed" {+ t.Fatalf("unexpected publish-enabled plugin response: status=%d body=%q", recorder.Code, recorder.Body.String())+ }+ if recorder := request(model.RoleReader, "/plugins/user-disabled/index.js"); recorder.Code != http.StatusForbidden {+ t.Fatalf("user-disabled plugin should be forbidden in publish, got %d", recorder.Code)+ }+ if recorder := request(model.RoleAdministrator, "/plugins/user-disabled/index.js"); recorder.Code != http.StatusOK ||+ recorder.Body.String() != "user-disabled" {+ t.Fatalf("unexpected administrator plugin response: status=%d body=%q", recorder.Code, recorder.Body.String())+ }+}diff --git a/kernel/util/websocket.go b/kernel/util/websocket.goindex c72bcbdcea..2a2c523f2e 100644--- a/kernel/util/websocket.go+++ b/kernel/util/websocket.go@@ -104,13 +104,21 @@ func BroadcastByType(typ, cmd string, code int, msg string, data any) {}func SessionsByType(typ string) (ret []*melody.Session) {+ return sessionsByType(typ, false)+}++func publishSessionsByType(typ string) (ret []*melody.Session) {+ return sessionsByType(typ, true)+}++func sessionsByType(typ string, publish bool) (ret []*melody.Session) {ret = []*melody.Session{}sessions.Range(func(key, value any) bool {appSessions := value.(*sync.Map)appSessions.Range(func(key, value any) bool {session := value.(*melody.Session)- if isPublishSession(session) {+ if isPublishSession(session) != publish {return true}if t, ok := session.Get("type"); ok && typ == t {@@ -262,6 +270,15 @@ func ReloadUI() {BroadcastByType("main", "reloadui", 0, "", nil)}+// ReloadPublishServiceSessions 通知所有已打开的发布服务页面刷新,使发布插件设置立即生效。+func ReloadPublishServiceSessions() {+ for _, session := range publishSessionsByType("main") {+ event := NewResult()+ event.Cmd = "reloadpublishpage"+ session.Write(event.Bytes())+ }+}+func PushTxErr(msg string, code int, data any) {BroadcastByType("main", "txerr", code, msg, data)}diff --git a/kernel/util/websocket_test.go b/kernel/util/websocket_test.goindex 469b663f04..c6f5ef0cdf 100644--- a/kernel/util/websocket_test.go+++ b/kernel/util/websocket_test.go@@ -87,4 +87,9 @@ func TestSessionsByTypeExcludesPublishSession(t *testing.T) {if len(actual) != 1 || actual[0] != regularSession {t.Fatalf("SessionsByType() returned %d sessions, want only the regular session", len(actual))}++ publishActual := publishSessionsByType(sessionType)+ if len(publishActual) != 1 || publishActual[0] != publishSession {+ t.Fatalf("publishSessionsByType() returned %d sessions, want only the publish session", len(publishActual))+ }}