alfred/command/gourl/gourl.go
2026-03-28 19:27:32 +08:00

121 lines
2.7 KiB
Go

package gourl
import (
"fmt"
"os"
aw "github.com/deanishe/awgo"
"gopkg.in/yaml.v3"
"gitea.micah.wiki/pandora/alfred/model"
"gitea.micah.wiki/pandora/alfred/pkg/logx"
"gitea.micah.wiki/pandora/alfred/pkg/stringx"
)
func getDefault() map[string][]*URLInfo {
return map[string][]*URLInfo{
"github": {{
Key: "github",
Title: "Github",
URL: "https://github.com/",
}},
"doubao": {{
Key: "doubao",
Title: "豆包",
URL: "https://www.doubao.com/chat",
}},
}
}
func Do(args []string) []*model.Item {
if len(args) == 0 {
return nil
}
logx.Info("gourl: %s", args[0])
urlMap := GetConfig()
if len(urlMap) == 0 {
logx.Info("配置文件未找到")
urlMap = getDefault()
}
if urls, ok := urlMap[args[0]]; ok {
logx.Info("go value: %+v", urls)
items := make([]*model.Item, 0)
if len(urls) > 0 {
for _, v := range urls {
items = append(items, &model.Item{
Title: fmt.Sprintf("回车 → 在浏览器打开 %s", v.Title),
Subtitle: stringx.NewStrPoint(v.URL),
UID: stringx.NewStrPoint("gourl-open-url"),
Arg: []string{"goto", v.URL},
Valid: true,
Icon: aw.IconNetwork,
})
}
}
return items
}
gotoConfigFile := os.Getenv("goto_config")
return []*model.Item{
{
Title: fmt.Sprintf("未找到 %s 相关跳转url配置", args[0]),
Subtitle: stringx.NewStrPoint(fmt.Sprintf("配置地址: %s", gotoConfigFile)),
UID: stringx.NewStrPoint("gourl-open-url"),
Arg: []string{"copytext", gotoConfigFile},
Valid: true,
Icon: aw.IconNetwork,
},
}
}
type URLInfo struct {
Key string `yaml:"key"`
Title string `yaml:"title"`
URL string `yaml:"url"`
}
type Config struct {
GoToConfig map[string][]*URLInfo `yaml:"goto_config"`
}
func GetConfig() map[string][]*URLInfo {
logx.Info("GetConfig start.")
cfgFile := os.Getenv("goto_config")
if cfgFile == "" {
logx.Info("读取配置文件为空")
return getDefault()
}
logx.Info(cfgFile)
// 读取配置文件内容
data, err := os.ReadFile(cfgFile)
if err != nil {
logx.Info("读取配置文件失败: %v", err)
return getDefault()
}
// 解析 YAML 到结构体
var cfg Config
if err = yaml.Unmarshal(data, &cfg); err != nil {
logx.Info("解析 YAML 失败: %v", err)
return getDefault()
}
if len(cfg.GoToConfig) == 0 {
logx.Info("读取配置文件未找到数据")
return getDefault()
}
c := make(map[string][]*URLInfo)
for _, list := range cfg.GoToConfig {
for _, info := range list {
for i := 1; i <= len(info.Key); i++ {
key := info.Key[:i]
v, ok := c[key]
if !ok {
v = make([]*URLInfo, 0)
}
v = append(v, info)
c[key] = v
}
}
}
logx.Info("config size: ", len(c))
return c
}