neko/pkg/types/plugins.go

92 lines
1.8 KiB
Go
Raw Normal View History

2022-04-16 07:28:00 +12:00
package types
import (
2022-04-19 22:14:59 +12:00
"errors"
2024-06-17 02:42:32 +12:00
"fmt"
"strings"
2022-04-19 22:14:59 +12:00
2024-06-17 02:42:32 +12:00
"github.com/demodesk/neko/pkg/utils"
2022-04-16 07:28:00 +12:00
"github.com/spf13/cobra"
)
2024-06-17 02:42:32 +12:00
var (
ErrPluginSettingsNotFound = errors.New("plugin settings not found")
)
2022-04-16 07:28:00 +12:00
type Plugin interface {
2022-04-19 22:14:59 +12:00
Name() string
2022-04-16 07:28:00 +12:00
Config() PluginConfig
2022-04-20 21:31:37 +12:00
Start(PluginManagers) error
2022-04-16 07:28:00 +12:00
Shutdown() error
}
2022-05-03 23:17:04 +12:00
type DependablePlugin interface {
Plugin
DependsOn() []string
}
2022-04-19 22:14:59 +12:00
type ExposablePlugin interface {
Plugin
ExposeService() any
}
2022-04-16 07:28:00 +12:00
type PluginConfig interface {
Init(cmd *cobra.Command) error
Set()
}
type PluginMetadata struct {
Name string
IsDependable bool
IsExposable bool
DependsOn []string `json:",omitempty"`
}
2022-04-16 07:28:00 +12:00
type PluginManagers struct {
2022-04-19 22:14:59 +12:00
SessionManager SessionManager
WebSocketManager WebSocketManager
ApiManager ApiManager
LoadServiceFromPlugin func(string) (any, error)
}
func (p *PluginManagers) Validate() error {
if p.SessionManager == nil {
return errors.New("SessionManager is nil")
}
if p.WebSocketManager == nil {
return errors.New("WebSocketManager is nil")
}
if p.ApiManager == nil {
return errors.New("ApiManager is nil")
}
if p.LoadServiceFromPlugin == nil {
return errors.New("LoadServiceFromPlugin is nil")
}
return nil
2022-04-16 07:28:00 +12:00
}
2024-06-17 02:42:32 +12:00
type PluginSettings map[string]any
func (p PluginSettings) Unmarshal(name string, def any) error {
if p == nil {
return fmt.Errorf("%w: %s", ErrPluginSettingsNotFound, name)
}
// loop through the plugin settings and take only the one that starts with the name
// because the settings are stored in a map["plugin_name.setting_name"] = value
newMap := make(map[string]any)
for k, v := range p {
if strings.HasPrefix(k, name+".") {
newMap[strings.TrimPrefix(k, name+".")] = v
}
}
fmt.Printf("newMap: %+v\n", newMap)
if len(newMap) == 0 {
2024-06-17 02:42:32 +12:00
return fmt.Errorf("%w: %s", ErrPluginSettingsNotFound, name)
}
return utils.Decode(newMap, def)
2024-06-17 02:42:32 +12:00
}