aliyunpan/internal/plugins/plugin_manager.go

99 lines
2.4 KiB
Go
Raw Normal View History

2022-04-20 14:14:18 +08:00
package plugins
2022-04-19 20:23:17 +08:00
import (
"fmt"
2022-04-20 09:49:16 +08:00
"github.com/tickstep/aliyunpan/internal/config"
2024-03-02 00:55:46 +08:00
"github.com/tickstep/aliyunpan/internal/global"
2022-04-19 20:23:17 +08:00
"github.com/tickstep/library-go/logger"
"io/ioutil"
"os"
"path"
"path/filepath"
"strings"
)
type (
PluginManager struct {
PluginPath string
}
)
2022-04-20 14:14:18 +08:00
func GetContext(user *config.PanUser) *Context {
2022-06-14 21:05:40 +08:00
if user == nil {
return &Context{
AppName: "aliyunpan",
2024-03-02 00:55:46 +08:00
Version: global.AppVersion,
2022-06-14 21:05:40 +08:00
UserId: "",
Nickname: "",
FileDriveId: "",
AlbumDriveId: "",
}
}
2022-04-20 14:14:18 +08:00
return &Context{
AppName: "aliyunpan",
2024-03-02 00:55:46 +08:00
Version: global.AppVersion,
2022-04-20 14:14:18 +08:00
UserId: user.UserId,
Nickname: user.Nickname,
FileDriveId: user.DriveList.GetFileDriveId(),
AlbumDriveId: user.DriveList.GetFileDriveId(),
}
}
func NewPluginManager(pluginDir string) *PluginManager {
2022-04-20 09:49:16 +08:00
return &PluginManager{
2022-04-20 14:14:18 +08:00
PluginPath: pluginDir,
2022-04-20 09:49:16 +08:00
}
2022-04-19 20:23:17 +08:00
}
func (p *PluginManager) SetPluginPath(pluginPath string) error {
if fi, err := os.Stat(pluginPath); err == nil && fi.IsDir() {
p.PluginPath = filepath.Clean(pluginPath)
} else {
return fmt.Errorf("path must be a folder")
}
return nil
}
func (p *PluginManager) GetPlugin() (Plugin, error) {
2022-04-20 14:14:18 +08:00
// js plugins folder
// only support js plugins right now
2022-04-19 20:23:17 +08:00
jsPluginPath := path.Clean(p.PluginPath + string(os.PathSeparator) + "js")
if fi, err := os.Stat(jsPluginPath); err == nil && fi.IsDir() {
2022-04-20 14:14:18 +08:00
jsPlugin := NewJsPlugin()
2022-04-19 20:23:17 +08:00
if jsPlugin.Start() != nil {
logger.Verbosef("初始化JS脚本错误\n")
return interface{}(NewIdlePlugin()).(Plugin), nil
}
jsPluginValid := false
if files, e := ioutil.ReadDir(jsPluginPath); e == nil {
for _, f := range files {
if !f.IsDir() {
2022-04-20 21:56:47 +08:00
if strings.HasPrefix(strings.ToLower(f.Name()), ".") || strings.HasPrefix(strings.ToLower(f.Name()), "~") {
continue
}
2022-04-19 20:23:17 +08:00
if strings.HasSuffix(strings.ToLower(f.Name()), ".js") {
// this is a js file
bytes, re := ioutil.ReadFile(path.Clean(jsPluginPath + string(os.PathSeparator) + f.Name()))
if re != nil {
logger.Verbosef("读取JS脚本错误: %s\n", re)
continue
}
var script = string(bytes)
if jsPlugin.LoadScript(script) == nil {
jsPluginValid = true
logger.Verbosef("加载JS脚本成功: %s\n", f.Name())
}
}
}
}
}
if jsPluginValid {
return interface{}(jsPlugin).(Plugin), nil
}
}
2022-04-20 14:14:18 +08:00
// default idle plugins
2022-04-19 20:23:17 +08:00
return interface{}(NewIdlePlugin()).(Plugin), nil
}