Files
qwqcode cf7725edba refactor(go): bump the module version and support go install (#979)
BREAKING CHANGE: The original Go module name was `github.com/ArtalkJS/Artalk`, which has now been modified to `github.com/artalkjs/artalk/v2` (all lowercase). This change may affect the CI pipeline or other areas if you are compiling the Artalk server and have specified the fixed Go module name. Regarding the original `-ldflags -X github.com/ArtalkJS/Artalk/internal/config.Version` and `CommitHash` definitions, please remove them, as they are now obsolete. The `Version` has been hardcoded into the Go code, and the `CommitHash` is now read from the Go build info via runtime/debug’s vcs.revision value. This change only affects the server developers and does not impact the frontend UI client.
2024-09-18 21:43:43 +08:00

93 lines
1.6 KiB
Go

package email
import (
"fmt"
"sync"
"github.com/artalkjs/artalk/v2/internal/config"
"github.com/artalkjs/artalk/v2/internal/log"
)
type EmailConf struct {
config.EmailConf
Sender Sender
OnSendSuccess func(email *Email)
}
type EmailQueue struct {
conf EmailConf
sender Sender
ch chan *Email
mux sync.Mutex
closed bool
}
// Initialize Email Queue
func NewQueue(conf EmailConf) *EmailQueue {
queue := &EmailQueue{
conf: conf,
}
// init email queue
queue.ch = make(chan *Email, conf.Queue.BufferSize)
log.Debug("[Email] Email Queue initialize complete")
// init email sender
if conf.Sender != nil {
queue.sender = conf.Sender
} else {
if sender, err := NewSender(queue.conf); err == nil {
queue.sender = sender
} else {
log.Error("[Email] Email Sender initialize failed: ", err)
}
}
// init queue worker
go func() {
for email := range queue.ch {
queue.handleEmail(email)
}
}()
return queue
}
func (q *EmailQueue) handleEmail(email *Email) {
log.Debug(fmt.Sprintf("[Email] Sending an email %+v: ", email))
if q.sender == nil {
log.Error("[Email] Email Sender is nil")
return
}
if isOK := q.sender.Send(email); isOK {
if q.conf.OnSendSuccess != nil {
q.conf.OnSendSuccess(email)
}
} else {
log.Errorf("[Email] Failed send email to addr: %s", email.ToAddr)
}
}
// Add an email to the sending queue
func (q *EmailQueue) Push(email *Email) {
if q.closed {
log.Error("[Email] Queue closed, dropping email")
return
}
q.ch <- email
}
func (q *EmailQueue) Close() {
q.mux.Lock()
defer q.mux.Unlock()
if !q.closed {
close(q.ch)
q.closed = true
}
}