update plugin management

This commit is contained in:
aynakeya
2024-04-15 14:00:48 -07:00
parent 139f331a14
commit fbf8c7f149
9 changed files with 243 additions and 162 deletions

View File

@@ -57,10 +57,6 @@ func main() {
time.Sleep(1 * time.Second)
global.EventManager.Start()
}()
//plugins := []adapter.Plugin{diange.NewDiange(mainController), qiege.NewQiege(mainController),
// textinfo.NewTextInfo(mainController), webinfo.NewWebInfo(mainController),
// wylogin.NewWYLogin(mainController)}
//mainController.LoadPlugins(plugins...)
gui.MainWindow.ShowAndRun()
internal.Stop()
global.EventManager.Stop()
@@ -70,30 +66,3 @@ func main() {
_ = config.SaveToConfigFile(config.ConfigPath)
global.Logger.Info("================Program End================")
}
////go:embed all:../webgui/frontend/dist
//var assets embed.FS
//
//func main() {
// // Create an instance of the app structure
// app := webgui.NewApp()
//
// // Create application with options
// err := wails.Run(&options.App{
// Title: "AynaLivePlayer",
// Width: 1024,
// Height: 768,
// AssetServer: &assetserver.Options{
// Assets: assets,
// },
// BackgroundColour: &options.RGBA{R: 27, G: 38, B: 54, A: 1},
// OnStartup: app.Startup,
// Bind: []interface{}{
// app,
// },
// })
//
// if err != nil {
// println("Error:", err.Error())
// }
//}

View File

@@ -332,6 +332,18 @@
"en": "Max Queue",
"zh-CN": "最大点歌数"
},
"plugin.diange.source.command": {
"en": "command",
"zh-CN": "命令"
},
"plugin.diange.source.enable": {
"en": "enable",
"zh-CN": "启用"
},
"plugin.diange.source.priority": {
"en": "priority",
"zh-CN": "优先级"
},
"plugin.diange.source_cmd": {
"en": "Source Command",
"zh-CN": "来源点歌命令"
@@ -381,8 +393,8 @@
"zh-CN": "管理员"
},
"plugin.qiege.custom_cmd": {
"en": "Custom Command (Default one still works)",
"zh-CN": "自定义命令 (默认的依然可用)"
"en": "Custom Command",
"zh-CN": "自定义命令"
},
"plugin.qiege.description": {
"en": "Basic Qiege configuration",

7
core/model/plugin.go Normal file
View File

@@ -0,0 +1,7 @@
package model
type Plugin interface {
Name() string
Enable() error
Disable() error
}

View File

@@ -5,7 +5,10 @@ import (
"AynaLivePlayer/internal/liveroom"
"AynaLivePlayer/internal/player"
"AynaLivePlayer/internal/playlist"
"AynaLivePlayer/internal/plugins"
"AynaLivePlayer/internal/source"
"AynaLivePlayer/plugin/diange"
"AynaLivePlayer/plugin/qiege"
)
func Initialize() {
@@ -14,10 +17,13 @@ func Initialize() {
playlist.Initialize()
controller.Initialize()
liveroom.Initialize()
plugins.Initialize()
plugins.LoadPlugins(diange.NewDiange(), qiege.NewQiege())
}
func Stop() {
liveroom.StopAndSave()
playlist.Close()
player.StopMpvPlayer()
plugins.ClosePlugins()
}

View File

@@ -0,0 +1,39 @@
package plugins
import (
"AynaLivePlayer/core/model"
"AynaLivePlayer/global"
"AynaLivePlayer/pkg/logger"
)
var plugins []model.Plugin = make([]model.Plugin, 0)
var log logger.ILogger
func Initialize() {
plugins = make([]model.Plugin, 0)
log = global.Logger.WithPrefix("Plugin")
}
func LoadPlugin(plugin model.Plugin) {
log.Info("[Plugin] Loading plugin: " + plugin.Name())
if err := plugin.Enable(); err != nil {
log.Warnf("[Plugin] Failed to load plugin: %s, %s", plugin.Name(), err)
return
}
plugins = append(plugins, plugin)
}
func LoadPlugins(plugins ...model.Plugin) {
for _, plugin := range plugins {
LoadPlugin(plugin)
}
}
func ClosePlugins() {
for _, plugin := range plugins {
if err := plugin.Disable(); err != nil {
log.Warnf("[Plugin] Failed to close plugin: %s, %s", plugin.Name(), err)
continue
}
}
}

View File

@@ -1,46 +0,0 @@
package todo
import (
"AynaLivePlayer/core/adapter"
"github.com/sirupsen/logrus"
)
type PluginController struct {
plugins map[string]adapter.Plugin
log adapter.ILogger
}
func NewPluginController(log adapter.ILogger) adapter.IPluginController {
return &PluginController{
plugins: make(map[string]adapter.Plugin),
log: log,
}
}
func (p *PluginController) LoadPlugin(plugin adapter.Plugin) {
p.log.Info("[Plugin] Loading plugin: " + plugin.Name())
if _, ok := p.plugins[plugin.Name()]; ok {
logrus.Warnf("[Plugin] plugin with same name already exists, skip")
return
}
if err := plugin.Enable(); err != nil {
p.log.Warnf("[Plugin] Failed to load plugin: %s, %s", plugin.Name(), err)
return
}
p.plugins[plugin.Name()] = plugin
}
func (p *PluginController) LoadPlugins(plugins ...adapter.Plugin) {
for _, plugin := range plugins {
p.LoadPlugin(plugin)
}
}
func (p *PluginController) ClosePlugins() {
for _, plugin := range p.plugins {
if err := plugin.Disable(); err != nil {
p.log.Warnf("[Plugin] Failed to close plugin: %s, %s", plugin.Name(), err)
continue
}
}
}

View File

@@ -1,20 +1,30 @@
package diange
import (
"AynaLivePlayer/core/events"
"AynaLivePlayer/core/model"
"AynaLivePlayer/global"
"AynaLivePlayer/gui"
"AynaLivePlayer/gui/component"
"AynaLivePlayer/pkg/config"
"AynaLivePlayer/pkg/event"
"AynaLivePlayer/pkg/i18n"
"AynaLivePlayer/pkg/logger"
"fyne.io/fyne/v2"
"fyne.io/fyne/v2/container"
"fyne.io/fyne/v2/data/binding"
"fyne.io/fyne/v2/widget"
"github.com/AynaLivePlayer/miaosic"
"sort"
"strings"
"time"
)
const MODULE_CMD_DIANGE = "CMD.DianGe"
type sourceConfig struct {
Enable bool `json:"enable"`
Command string `json:"command"`
Priority int `json:"priority"`
}
type Diange struct {
config.BaseConfig
@@ -26,9 +36,13 @@ type Diange struct {
QueueMax int
UserCoolDown int
CustomCMD string
SourceCMD []string
cooldowns map[string]int
panel fyne.CanvasObject
SourceConfigPath string
currentQueueLength int
sourceConfigs map[string]*sourceConfig
cooldowns map[string]int
panel fyne.CanvasObject
log logger.ILogger
}
func NewDiange() *Diange {
@@ -38,9 +52,34 @@ func NewDiange() *Diange {
AdminPermission: true,
QueueMax: 128,
UserCoolDown: -1,
CustomCMD: "add",
SourceCMD: make([]string, 0),
cooldowns: make(map[string]int),
CustomCMD: "点歌",
SourceConfigPath: "diange.json",
currentQueueLength: 0,
sourceConfigs: map[string]*sourceConfig{
"netease": {
Enable: true,
Command: "点w歌",
Priority: 1,
},
"kuwo": {
Enable: true,
Command: "点k歌",
Priority: 2,
},
"bilibili-video": {
Enable: true,
Command: "点b歌",
Priority: 3,
},
"local": {
Enable: true,
Command: "点l歌",
Priority: 4,
},
},
cooldowns: make(map[string]int),
log: global.Logger.WithPrefix("Plugin.Logger"),
}
}
@@ -48,11 +87,27 @@ func (d *Diange) Name() string {
return "Diange"
}
func (c *Diange) OnLoad() {
_ = config.LoadJson(c.SourceConfigPath, &c.sourceConfigs)
}
func (c *Diange) OnSave() {
_ = config.SaveJson(c.SourceConfigPath, c.sourceConfigs)
}
func (d *Diange) Enable() error {
config.LoadConfig(d)
d.initCMD()
d.contro.LiveRooms().AddDanmuCommand(d)
gui.AddConfigLayout(d)
global.EventManager.RegisterA(
events.LiveRoomMessageReceive,
"plugin.diange.message",
d.handleMessage)
global.EventManager.RegisterA(
events.PlaylistDetailUpdate(model.PlaylistIDPlayer),
"plugin.diange.queue.update",
func(event *event.Event) {
d.currentQueueLength = len(event.Data.(events.PlaylistDetailUpdateEvent).Medias)
})
return nil
}
@@ -60,71 +115,84 @@ func (d *Diange) Disable() error {
return nil
}
func (d *Diange) initCMD() {
if len(d.SourceCMD) == len(d.contro.Provider().GetPriority()) {
return
}
if len(d.SourceCMD) > len(d.contro.Provider().GetPriority()) {
d.SourceCMD = d.SourceCMD[:len(d.contro.Provider().GetPriority())]
return
}
for i := len(d.SourceCMD); i < len(d.contro.Provider().GetPriority()); i++ {
d.SourceCMD = append(d.SourceCMD, "点歌"+d.contro.Provider().GetPriority()[i])
}
}
// isCMD return int if the commmand name matches our command
// -1 = not match, 0 = normal command, 1+ = source command
func (d *Diange) isCMD(cmd string) int {
if cmd == "点歌" || cmd == d.CustomCMD {
return 0
}
for index, c := range d.SourceCMD {
if cmd == c {
return index + 1
func (d *Diange) getSources() []string {
sources := []string{}
for source, c := range d.sourceConfigs {
if c.Enable {
sources = append(sources, source)
}
}
return -1
sort.Slice(sources, func(i, j int) bool {
return d.sourceConfigs[sources[i]].Priority < d.sourceConfigs[sources[j]].Priority
})
return sources
}
func (d *Diange) Match(command string) bool {
return d.isCMD(command) >= 0
func (d *Diange) getSource(cmd string) []string {
if cmd == d.CustomCMD {
return d.getSources()
}
sources := []string{}
for source, c := range d.sourceConfigs {
if c.Command == cmd {
sources = append(sources, source)
}
}
return sources
}
func (d *Diange) Execute(command string, args []string, danmu *model.DanmuMessage) {
d.log.Infof("%s(%s) Execute command: %s %s", danmu.User.Username, danmu.User.Uid, command, args)
func (d *Diange) handleMessage(event *event.Event) {
message := event.Data.(events.LiveRoomMessageReceiveEvent).Message
msgs := strings.Split(message.Message, " ")
if len(msgs) < 2 || len(msgs[0]) == 0 || len(msgs[1]) == 0 {
return
}
sources := d.getSource(msgs[0])
if len(sources) == 0 {
return
}
// if queue is full, return
if d.contro.Playlists().GetCurrent().Size() >= d.QueueMax {
if d.currentQueueLength >= d.QueueMax {
d.log.Info("Queue is full, ignore diange")
return
}
// if in user cool down, return
ct := int(time.Now().Unix())
if (ct - d.cooldowns[danmu.User.Uid]) <= d.UserCoolDown {
d.log.Infof("User %s(%s) still in cool down period, diange failed", danmu.User.Username, danmu.User.Uid)
if (ct - d.cooldowns[message.User.Uid]) <= d.UserCoolDown {
d.log.Infof("User %s(%s) still in cool down period, diange failed", message.User.Username, message.User.Uid)
return
}
cmdType := d.isCMD(command)
keyword := strings.Join(args, " ")
perm := d.UserPermission
d.log.Debugf("user permission check: ", perm)
perm = perm || (d.PrivilegePermission && (danmu.User.Privilege > 0))
d.log.Debugf("privilege permission check: ", perm)
perm = perm || (d.AdminPermission && (danmu.User.Admin))
d.log.Debugf("admin permission check: ", perm)
d.log.Debug("user permission check: ", perm)
perm = perm || (d.PrivilegePermission && (message.User.Privilege > 0))
d.log.Debug("privilege permission check: ", perm)
perm = perm || (d.AdminPermission && (message.User.Admin))
d.log.Debug("admin permission check: ", perm)
// if use medal check
if d.MedalName != "" && d.MedalPermission >= 0 {
perm = perm || ((danmu.User.Medal.Name == d.MedalName) && danmu.User.Medal.Level >= d.MedalPermission)
perm = perm || ((message.User.Medal.Name == d.MedalName) && message.User.Medal.Level >= d.MedalPermission)
}
if !perm {
return
}
// reset cool down
d.cooldowns[danmu.User.Uid] = ct
if cmdType == 0 {
d.contro.PlayControl().Add(keyword, &danmu.User)
} else {
d.contro.PlayControl().AddWithProvider(keyword, d.contro.Provider().GetPriority()[cmdType-1], &danmu.User)
d.cooldowns[message.User.Uid] = ct
keywords := strings.Join(msgs[1:], " ")
for _, source := range sources {
medias, err := miaosic.SearchByProvider(source, keywords, 1, 10)
if len(medias) == 0 || err != nil {
continue
}
global.EventManager.CallA(
events.PlaylistInsertCmd(model.PlaylistIDPlayer),
events.PlaylistInsertCmdEvent{
Position: -1,
Media: model.Media{
Info: medias[0],
User: message.User,
},
})
break
}
}
@@ -172,17 +240,22 @@ func (d *Diange) CreatePanel() fyne.CanvasObject {
widget.NewLabel(i18n.T("plugin.diange.custom_cmd")), nil,
widget.NewEntryWithData(binding.BindString(&d.CustomCMD)),
)
sourceCmds := []fyne.CanvasObject{}
for i, _ := range d.SourceCMD {
sourceCmds = append(
sourceCmds,
container.NewBorder(
nil, nil, widget.NewLabel(d.contro.Provider().GetPriority()[i]), nil,
widget.NewEntryWithData(binding.BindString(&d.SourceCMD[i]))))
sourceCfgs := []fyne.CanvasObject{}
for source, cfg := range d.sourceConfigs {
sourceCfgs = append(
sourceCfgs, container.NewGridWithColumns(2,
widget.NewLabel(source),
widget.NewCheckWithData(i18n.T("plugin.diange.source.enable"), binding.BindBool(&cfg.Enable)),
widget.NewLabel(i18n.T("plugin.diange.source.priority")),
widget.NewEntryWithData(binding.IntToString(binding.BindInt(&cfg.Priority))),
widget.NewLabel(i18n.T("plugin.diange.source.command")),
widget.NewEntryWithData(binding.BindString(&cfg.Command)),
),
)
}
dgSourceCMD := container.NewBorder(
nil, nil, widget.NewLabel(i18n.T("plugin.diange.source_cmd")), nil,
container.NewVBox(sourceCmds...))
container.NewVBox(sourceCfgs...))
d.panel = container.NewVBox(dgPerm, dgMdPerm, dgQueue, dgCoolDown, dgShortCut, dgSourceCMD)
return d.panel
}

View File

@@ -1,16 +1,18 @@
package qiege
import (
"AynaLivePlayer/core/adapter"
"AynaLivePlayer/core/model"
"AynaLivePlayer/core/events"
"AynaLivePlayer/global"
"AynaLivePlayer/gui"
"AynaLivePlayer/gui/component"
"AynaLivePlayer/pkg/config"
"AynaLivePlayer/pkg/event"
"AynaLivePlayer/pkg/i18n"
"fyne.io/fyne/v2"
"fyne.io/fyne/v2/container"
"fyne.io/fyne/v2/data/binding"
"fyne.io/fyne/v2/widget"
"strings"
)
type Qiege struct {
@@ -19,15 +21,16 @@ type Qiege struct {
PrivilegePermission bool
AdminPermission bool
CustomCMD string
currentUid string
panel fyne.CanvasObject
}
func NewQiege(ctr adapter.IControlBridge) *Qiege {
func NewQiege() *Qiege {
return &Qiege{
UserPermission: true,
PrivilegePermission: true,
AdminPermission: true,
CustomCMD: "skip",
CustomCMD: "切歌",
}
}
@@ -37,8 +40,24 @@ func (d *Qiege) Name() string {
func (d *Qiege) Enable() error {
config.LoadConfig(d)
d.ctr.LiveRooms().AddDanmuCommand(d)
gui.AddConfigLayout(d)
global.EventManager.RegisterA(
events.LiveRoomMessageReceive,
"plugin.qiege.message",
d.handleMessage)
global.EventManager.RegisterA(
events.PlayerPlayingUpdate,
"plugin.qiege.playing",
func(event *event.Event) {
data := event.Data.(events.PlayerPlayingUpdateEvent)
if data.Removed {
d.currentUid = ""
}
if !data.Media.IsLiveRoomUser() {
d.currentUid = ""
}
d.currentUid = data.Media.DanmuUser().Uid
})
return nil
}
@@ -46,28 +65,30 @@ func (d *Qiege) Disable() error {
return nil
}
func (d *Qiege) Match(command string) bool {
for _, c := range []string{"切歌", d.CustomCMD} {
if command == c {
return true
}
func (d *Qiege) handleMessage(event *event.Event) {
message := event.Data.(events.LiveRoomMessageReceiveEvent).Message
msgs := strings.Split(message.Message, " ")
if len(msgs) < 1 || len(msgs[0]) == 0 {
return
}
return false
}
func (d *Qiege) Execute(command string, args []string, danmu *model.DanmuMessage) {
if d.UserPermission && (d.ctr.PlayControl().GetPlaying() != nil) {
if d.ctr.PlayControl().GetPlaying().DanmuUser() != nil && d.ctr.PlayControl().GetPlaying().DanmuUser().Uid == danmu.User.Uid {
d.ctr.PlayControl().PlayNext()
if d.UserPermission {
if d.currentUid == message.User.Uid {
global.EventManager.CallA(
events.PlayerPlayNextCmd,
events.PlayerPlayNextCmdEvent{})
return
}
}
if d.PrivilegePermission && danmu.User.Privilege > 0 {
d.ctr.PlayControl().PlayNext()
if d.PrivilegePermission && message.User.Privilege > 0 {
global.EventManager.CallA(
events.PlayerPlayNextCmd,
events.PlayerPlayNextCmdEvent{})
return
}
if d.AdminPermission && danmu.User.Admin {
d.ctr.PlayControl().PlayNext()
if d.AdminPermission && message.User.Admin {
global.EventManager.CallA(
events.PlayerPlayNextCmd,
events.PlayerPlayNextCmdEvent{})
return
}
}