Compare commits

..
4 Commits
Author SHA1 Message Date
Akizon 1b76b7ad5b js通知沿用旧版本的逻辑 2026-10-14 17:00:19 +08:00
Akizon 13cbdca545 和浏览器1起协商ws压缩算法 2026-10-10 17:32:08 +08:00
Akizon e48aa1e769 加1个通知升级提醒 2026-10-08 10:04:56 +08:00
Akizon a68704a425 js通知先加回来 2026-10-08 09:31:51 +08:00
10 changed files with 188 additions and 12 deletions

No files matched your search

+15 -4
View File
@@ -186,6 +186,13 @@ const (
// versionID 是当前构建的版本标识,由 SetVersionID 在 Initialize 前注入。
var versionID string
// nil means a fresh install; an empty value means an unmarked legacy install.
var lastRunVersion *string
func LastRunVersion() *string {
return lastRunVersion
}
// dbFileExistedAtStartup 记录本次进程启动、打开数据库之前 komari.db 是否已存在,
// 用于区分“全新安装”与“从旧版升级(无版本标记)”。在 doInitialize 打开数据库
// 之前采集。
@@ -221,13 +228,17 @@ func resolveDatabaseFile() string {
//
// 备份失败不阻止启动,但打印明确错误;备份成功(或无需备份)后写入/更新版本。
func backupOnVersionUpgrade() {
if versionID == "" {
return
}
prevVersion, readErr := config.GetAs[string](SystemVersionKey)
prevVersion = strings.TrimSpace(prevVersion)
versionRecorded := readErr == nil && prevVersion != ""
lastRunVersion = nil
if versionRecorded || dbFileExistedAtStartup {
lastRunVersion = &prevVersion
}
if versionID == "" {
return
}
// 版本未变化,无需备份。
if versionRecorded && prevVersion == versionID {
+21 -4
View File
@@ -4,19 +4,33 @@ package notifications
import (
"encoding/json"
"errors"
"github.com/komari-monitor/komari/database"
"github.com/komari-monitor/komari/database/models"
"github.com/komari-monitor/komari/internal/managedconfig"
"github.com/komari-monitor/komari/utils/messageSender"
"github.com/komari-monitor/komari/utils/messageSender/javascript"
"github.com/komari-monitor/komari/utils/messageSender/webhook"
)
// Initialize registers the built-in webhook channel and seeds its defaults.
func Initialize() error {
// Initialize registers the built-in channels and seeds their defaults.
func Initialize() (err error) {
if err := webhook.Register(); err != nil {
return err
}
registered := []string{"webhook"}
defer func() {
if err != nil {
for _, id := range registered {
err = errors.Join(err, messageSender.UnregisterNotificationChannel(id))
}
}
}()
if err := javascript.Register(); err != nil {
return err
}
registered = append(registered, javascript.ChannelID)
for _, item := range messageSender.ListNotificationChannels() {
if _, err := database.GetMessageSenderConfigByName(item.ID); err == nil {
continue
@@ -41,7 +55,10 @@ func Initialize() error {
return nil
}
// Shutdown unregisters the built-in webhook channel.
// Shutdown unregisters the built-in channels and releases their runtimes.
func Shutdown() error {
return messageSender.UnregisterNotificationChannel("webhook")
return errors.Join(
messageSender.UnregisterNotificationChannel(javascript.ChannelID),
messageSender.UnregisterNotificationChannel("webhook"),
)
}
@@ -0,0 +1,109 @@
package javascript
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"strings"
"sync"
"time"
"github.com/komari-monitor/komari/pkg/jsruntime"
"github.com/komari-monitor/komari/utils/messageSender"
"github.com/komari-monitor/komari/utils/messageSender/outboundhttp"
)
// DataDir confines notification scripts' filesystem and local module access.
var DataDir = "./data/notification/javascript"
// ChannelID is also the key of existing JavaScript configurations in the database.
const ChannelID = "Javascript"
const executionTimeout = 30 * time.Second
type JavaScriptSender struct {
mu sync.Mutex
script string
runtime *jsruntime.Runtime
}
func (j *JavaScriptSender) Send(ctx context.Context, notification messageSender.Notification, config map[string]any) error {
var addition Addition
if err := messageSender.DecodeConfiguration(config, &addition); err != nil {
return err
}
j.mu.Lock()
defer j.mu.Unlock()
if err := ctx.Err(); err != nil {
return err
}
if err := j.ensureRuntime(addition.Script); err != nil {
return err
}
if !j.runtime.HasFunction("sendEvent") {
return j.runtime.Call("sendMessage", notification.Message, notification.Title)
}
// Preserve the event's JSON field names and nested payloads for legacy scripts.
raw, err := json.Marshal(notification.Event)
if err != nil {
return fmt.Errorf("marshal notification event: %w", err)
}
var event map[string]any
if err := json.Unmarshal(raw, &event); err != nil {
return fmt.Errorf("decode notification event: %w", err)
}
return j.runtime.Call("sendEvent", event)
}
func (j *JavaScriptSender) ensureRuntime(script string) error {
if j.runtime != nil && j.script == script {
return nil
}
j.closeRuntime()
if strings.TrimSpace(script) == "" {
return errors.New("JavaScript notification script is not configured")
}
if err := os.MkdirAll(DataDir, 0755); err != nil {
return fmt.Errorf("create JavaScript notification directory: %w", err)
}
runtime, err := jsruntime.New(script, jsruntime.Options{
BaseDir: DataDir,
NodeJS: true,
Timeout: executionTimeout,
HTTPClient: outboundhttp.NewClient(executionTimeout),
})
if err != nil {
return err
}
if !runtime.HasFunction("sendMessage") {
runtime.Close()
return errors.New("sendMessage function not defined or not callable in script")
}
j.script = script
j.runtime = runtime
return nil
}
func (j *JavaScriptSender) closeRuntime() {
if j.runtime != nil {
j.runtime.Close()
j.runtime = nil
}
j.script = ""
}
func (j *JavaScriptSender) Unload() error {
j.mu.Lock()
defer j.mu.Unlock()
j.closeRuntime()
return nil
}
func Register() error {
return messageSender.RegisterNotificationChannel(ChannelID, messageSender.ManagedConfiguration("JavaScript", Addition{}), &JavaScriptSender{})
}
var _ messageSender.NotificationChannel = (*JavaScriptSender)(nil)
+5
View File
@@ -0,0 +1,5 @@
package javascript
type Addition struct {
Script string `json:"script" name:"Script" required:"true" type:"richtext" help:"Implement sendMessage(message, title) and optionally sendEvent(event). Return true or a Promise resolving to true. Available APIs include fetch, XMLHttpRequest, console, timers, Buffer and CommonJS require with Node compatibility modules. Files and local modules are confined to data/notification/javascript; command execution and listening on ports are disabled."`
}
+1 -1
View File
@@ -24,7 +24,7 @@ func EstablishConnection(c *gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error": "Require WebSocket upgrade"})
return
}
conn, err := api.UpgradeSafeConn(c)
conn, err := api.UpgradeSafeConn(c, api.EnableWebSocketCompression)
if err != nil {
closeSession(session_id)
return
+1 -1
View File
@@ -55,7 +55,7 @@ func RequestTerminal(c *gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "message": "Require WebSocket upgrade"})
return
}
conn, err := api.UpgradeSafeConn(c)
conn, err := api.UpgradeSafeConn(c, api.EnableWebSocketCompression)
if err != nil {
return
}
+1 -1
View File
@@ -19,7 +19,7 @@ func GetClients(c *gin.Context) {
return
}
// Upgrade the HTTP connection to a WebSocket connection
conn, err := UpgradeSafeConn(c)
conn, err := UpgradeSafeConn(c, EnableWebSocketCompression)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error": "Failed to upgrade to WebSocket." + err.Error()})
return
+9
View File
@@ -50,6 +50,11 @@ func init() {
Summary: "Get all settings",
Returns: "object",
})
RegisterWithGroupAndMeta("getLastRunVersion", rpc.RoleAdmin, adminGetLastRunVersion, &rpc.MethodMeta{
Name: "admin:getLastRunVersion",
Summary: "Get the version recorded before this startup",
Returns: "{ last_run_version: string | null }",
})
RegisterWithGroupAndMeta("editSettings", rpc.RoleAdmin, adminEditSettings, &rpc.MethodMeta{
Name: "admin:editSettings",
Summary: "Update settings (partial)",
@@ -112,6 +117,10 @@ func adminGetSettings(_ context.Context, _ *rpc.JsonRpcRequest) (any, *rpc.JsonR
return cst, nil
}
func adminGetLastRunVersion(_ context.Context, _ *rpc.JsonRpcRequest) (any, *rpc.JsonRpcError) {
return map[string]any{"last_run_version": dbcore.LastRunVersion()}, nil
}
// metricStoreConfigKeys 是与 metrics 独立数据库及 rollup 策略相关、需要
// 触发连接测试 + 热重载的配置键。
//
+25
View File
@@ -1,11 +1,36 @@
package jsonrpc
import (
"context"
"encoding/json"
"testing"
"github.com/komari-monitor/komari/database/dbcore"
"github.com/komari-monitor/komari/internal/metricstore"
)
func TestAdminGetLastRunVersion(t *testing.T) {
result, rpcErr := adminGetLastRunVersion(context.Background(), nil)
if rpcErr != nil {
t.Fatal(rpcErr)
}
data, err := json.Marshal(result)
if err != nil {
t.Fatal(err)
}
var payload struct {
LastRunVersion *string `json:"last_run_version"`
}
if err := json.Unmarshal(data, &payload); err != nil {
t.Fatal(err)
}
want := dbcore.LastRunVersion()
if (payload.LastRunVersion == nil) != (want == nil) ||
(want != nil && *payload.LastRunVersion != *want) {
t.Fatalf("unexpected last run version: %s", data)
}
}
func TestMetricKeysTouched(t *testing.T) {
if !metricKeysTouched(map[string]interface{}{metricstore.MetricDBDSNKey: "metrics.db"}) {
t.Fatal("metric database DSN must trigger metric store validation")
+1 -1
View File
@@ -89,7 +89,7 @@ func headerOrQueryTwoFACode(c *gin.Context) string {
}
func serveWebSocket(c *gin.Context) {
conn, err := api.UpgradeSafeConn(c)
conn, err := api.UpgradeSafeConn(c, api.EnableWebSocketCompression)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error": "Failed to upgrade to WebSocket." + err.Error()})
return