refactor: notifications

This commit is contained in:
yusing
2025-05-02 05:51:15 +08:00
parent 28d9a72908
commit 69ee8495d8
11 changed files with 202 additions and 104 deletions

View File

@@ -1,10 +1,7 @@
package notif
import (
"bytes"
"io"
"net/http"
"strings"
"github.com/rs/zerolog"
"github.com/yusing/go-proxy/internal/gperr"
@@ -13,18 +10,14 @@ import (
// See https://docs.ntfy.sh/publish
type Ntfy struct {
ProviderBase
Topic string `json:"topic"`
Style NtfyStyle `json:"style"`
Topic string `json:"topic"`
}
type NtfyStyle string
const (
NtfyStyleMarkdown NtfyStyle = "markdown"
NtfyStylePlain NtfyStyle = "plain"
)
// Validate implements the utils.CustomValidator interface.
func (n *Ntfy) Validate() gperr.Error {
if err := n.ProviderBase.Validate(); err != nil {
return err
}
if n.URL == "" {
return gperr.New("url is required")
}
@@ -34,16 +27,10 @@ func (n *Ntfy) Validate() gperr.Error {
if n.Topic[0] == '/' {
return gperr.New("topic should not start with a slash")
}
switch n.Style {
case "":
n.Style = NtfyStyleMarkdown
case NtfyStyleMarkdown, NtfyStylePlain:
default:
return gperr.Errorf("invalid style, expecting %q or %q, got %q", NtfyStyleMarkdown, NtfyStylePlain, n.Style)
}
return nil
}
// GetURL implements Provider.
func (n *Ntfy) GetURL() string {
if n.URL[len(n.URL)-1] == '/' {
return n.URL + n.Topic
@@ -51,23 +38,22 @@ func (n *Ntfy) GetURL() string {
return n.URL + "/" + n.Topic
}
// GetMIMEType implements Provider.
func (n *Ntfy) GetMIMEType() string {
return ""
}
// GetToken implements Provider.
func (n *Ntfy) GetToken() string {
return n.Token
}
func (n *Ntfy) MakeBody(logMsg *LogMessage) (io.Reader, error) {
switch n.Style {
case NtfyStyleMarkdown:
return strings.NewReader(formatMarkdown(logMsg.Extras)), nil
default:
return &bytes.Buffer{}, nil
}
// MarshalMessage implements Provider.
func (n *Ntfy) MarshalMessage(logMsg *LogMessage) ([]byte, error) {
return logMsg.Body.Format(n.Format)
}
// SetHeaders implements Provider.
func (n *Ntfy) SetHeaders(logMsg *LogMessage, headers http.Header) {
headers.Set("Title", logMsg.Title)
@@ -83,7 +69,7 @@ func (n *Ntfy) SetHeaders(logMsg *LogMessage, headers http.Header) {
headers.Set("Priority", "min")
}
if n.Style == NtfyStyleMarkdown {
if n.Format == LogFormatMarkdown {
headers.Set("Markdown", "yes")
}
}