mail/plugin.go
2025-08-01 00:54:13 +08:00

115 lines
2.6 KiB
Go

package mail
import (
"runtime"
"strings"
"apigo.cc/gojs"
"apigo.cc/gojs/goja"
"github.com/ssgo/config"
"github.com/ssgo/log"
"github.com/ssgo/u"
)
const pluginName = "mail"
type Config struct {
Mailbox map[string]*MailboxConfig
ClientName string
ClientVersion string
ClientOS string
ClientVendor string
ClientSupportURL string
}
type MailboxConfig struct {
SmtpHost string
SmtpPort int
ImapHost string
ImapPort int
Username string
Password string
SenderName string
SenderMail string
}
var conf = &Config{
Mailbox: make(map[string]*MailboxConfig),
ClientName: "Apigo Mail Client",
ClientVersion: "1.0.0",
ClientOS: runtime.GOOS,
ClientVendor: "apigo.cc",
ClientSupportURL: "https://apigo.cc/gojs/mail",
}
var defaultObject = &DefaultObject{}
var confAes *u.Aes = u.NewAes([]byte("?GQ$0K0GgLdO=f+~L68PLm$uhKr4'=tV"), []byte("VFs7@sK61cj^f?HZ"))
var objects = make(map[string]*Mailbox)
func init() {
tsCode := gojs.MakeTSCode(defaultObject)
gojs.Register("apigo.cc/gojs/"+pluginName, gojs.Module{
ObjectMaker: func(vm *goja.Runtime) gojs.Map {
config.LoadConfig(pluginName, conf)
for name, object := range conf.Mailbox {
objects[name] = defaultObject.New(object)
}
if defaultMailbox, err := defaultObject.Get("default"); err == nil {
defaultObject.Mailbox = defaultMailbox
} else if len(objects) == 0 {
log.DefaultLogger.Warning("no mailbox configured", "example for env.yml", "mail:\n mailbox:\n default:\n username: ****@***.***")
}
return gojs.ToMap(defaultObject)
},
TsCode: tsCode,
Desc: "mail api",
SetSSKey: func(key, iv []byte) {
confAes = u.NewAes(key, iv)
},
})
}
type DefaultObject struct {
*Mailbox
}
func (obj *DefaultObject) Get(name string) (*Mailbox, error) {
if o, ok := objects[name]; ok {
return o, nil
} else {
return nil, gojs.Err("mailbox [" + name + "] not configured")
}
}
func (obj *DefaultObject) New(conf *MailboxConfig) *Mailbox {
a := strings.SplitN(conf.Username, "@", 2)
if len(a) == 2 {
if conf.SmtpHost == "" {
conf.SmtpHost = "smtp." + a[1]
}
if conf.SmtpPort == 0 {
conf.SmtpPort = 465
}
if conf.ImapHost == "" {
conf.ImapHost = "imap." + a[1]
}
if conf.ImapPort == 0 {
conf.ImapPort = 993
}
}
if conf.SenderMail == "" {
conf.SenderMail = conf.Username
}
return &Mailbox{
smtpHost: conf.SmtpHost,
smtpPort: conf.SmtpPort,
imapHost: conf.ImapHost,
imapPort: conf.ImapPort,
username: conf.Username,
password: confAes.DecryptUrlBase64ToString(conf.Password),
senderName: conf.SenderName,
senderMail: conf.SenderMail,
}
}